microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.08k stars 12.37k forks source link

Export Typescript libraries as individual interfaces as well #38899

Open NikhilVerma opened 4 years ago

NikhilVerma commented 4 years ago

Search Terms

export library interface

Suggestion

Right now Typescript declares it's libraries using d.ts (e.g. lib.dom.d.ts) so if you include this in your project you get the entire DOM library and it's interfaces. This is great however it makes development of isomorphic code harder.

Your only option is to add the dom library to your NodeJS project. This means that consumers could accidentally write unsafe code.

My proposal is really simple. Along with existing d.ts imports, we also export (in a separate file) the interfaces for those libraries

Use Cases

Isomorphic code could be be implemented in an easier way. Right now we need to either include the whole library or use dependency injection. Which is not always trivial.

Here is an example of an issue encountered from the puppeteer repo - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/24419#issuecomment-637700421

Examples

import { Window } from 'typescript/interface/lib.dom'; // proposed path

window.alert('something'); // this will throw TS errors

page.evaluate(() => {
    // this will be fine and type checked according to window
    (window as Window).alert('something'); 
});

Checklist

My suggestion meets these guidelines:

MartinJohns commented 4 years ago

Wouldn't adding the lib-reference in the source file only already solve this issue?

/// <reference lib="..." />

My mistake, won't do. :-)

NikhilVerma commented 4 years ago

@MartinJohns when i used /// reference it actually includes the types for the whole project (it's similar to adding lib option in tsconfig.json)

And the Typescript documentation seems to suggest so: https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-lib-

For example, adding /// to one of the files in a compilation is equivalent to compiling with --lib es2017.string.