Let's say I have a project with two typescript files:
- a.ts
- b.ts.
My tsconfig.json:
{
"target": "ES5", // old browser support is required
"lib": ["dom", "es5"], //
"types": [] //
}
I left types setting empty as I don't want to pickup typings from any third party packages (e.g. @types/node typings installed as a dependency of webpack-dev-server package; details are HERE)
Now I decided to use some new JS feature and added the following line to a.ts file:
let clone = Object.assign({}, {a:1});
Luckily, compiler is smart enough to warn me with the following warning:
a.ts:1:20 - error TS2339: Property 'assign' does not exist on type 'ObjectConstructor'.
So I have to add a polyfill (e.g. CORE-JS package) and add an import statement to a.ts:
import 'core-js/modules/es.object.assign'
let clone = Object.assign({}, {a:1});
But typescript compiler is still not happy, as it doesn't have typings for my newly polyfilled assign method . I tried to install @types/core-js package and add its name to my tsconfig.json file, but it didn't work so I created my own type definition file object.d.ts:
interface ObjectConstructor {
assign(target: any, ...sources: any[]): any;
}
Everything started to work. Hooray!
Then, I added another new feature, but this time in b.ts file.
import 'core-js/modules/es.array.from'
console.log(Array.from('foo'));
And I also added a type definition for a new method (file array.d.ts):
interface ArrayConstructor {
from<T>(arrayLike: ArrayLike<T>): T[];
}
And now, as both my typing files are globally accessible, I can use Array.from in a.ts, and Object.assign in b.ts and that's a problem. Unless I add
import 'core-js/modules/es.object.assign'
to b.ts, the code won't work in old browsers and compiler won't tell me about it.
So, here are my questions:
- Is it possible to use type definitions from @types/core-js and expose types one by one (as I'm adding polyfills for them)?
- Is it possible to make my own type definitions visible to a particular files (not globally visible), so I'll have control over what is polyfilled in each file?
PS: I will not bundle my two files, as they have to be delivered separately. Extracting polyfill imports into a separate modules and later add imports to that module in each file is not a desired option for me, as it will potentially create references to polyfills which are not used in my files and I want to keep result files as small as possible.