ts-reset
ts-reset copied to clipboard
Make dynamic require imports return `unknown`
Currently, require
faces a similar problem to JSON.parse
, where it returns any
. Like JSON.parse
, I think this would be another great place to reset the return type to be unknown.
I.e.
var require: NodeRequire (id: string) => any
becomes
var require: NodeRequire (id: string) => unknown
To be fair: require
has intellisense on exported instances if I'm not mistaken.
So what exactly is the usecase of making it return an unknown
type?
To eleborate:
When importing like so:
const hi = require("pkg");
The variable hi
will contain all exported stuff and will show it in intellisense, where this may seem as any because it says so, it does not harm the typesafety in my opinion.
To be fair:
require
has intellisense on exported instances if I'm not mistaken.So what exactly is the usecase of making it return an
unknown
type?To eleborate:
When importing like so:
const hi = require("pkg");
The variable
hi
will contain all exported stuff and will show it in intellisense, where this may seem as any because it says so, it does not harm the typesafety in my opinion.
Yeah this is true when doing static imports, but if you're using require dynamically, for example
const importFile = (path: string): any => {
return require(path);
};
The default behaviour of this require is to return any
.
You're right about the intellisense stuff though so I'll investigate to see if theres a way to test this behaviour is maintained in the PR
Yeah this is true when doing static imports, but if you're using require dynamically, for example
const importFile = (path: string): any => { return require(path); };
The default behaviour of this require is to return
any
.You're right about the intellisense stuff though so I'll investigate to see if theres a way to test this behaviour is maintained in the PR
I've tested it in JS and no luck, does not change when you return unkown, the wrapper function will also not have any idea what is in there since you put a path
as import path.
Yep thats exactly what I mean. We can change the Require's default return type to be unknown
when its given a dynamic string such as in the above example (see here), then this function we can change to return unknown
which in my opinion makes more sense.
When doing top level require, JS's intellisense will still kick in. So this change would only affect the very limited use case of using require
when not knowing the path being passed in until runtime
I think top-level require
calls should be using the import = require()
syntax anyway, so this change should only affect dynamic require
calls.