I'm reading through the React source code recently, and just found all the files are .js instead of .ts
What's more is, in those .js files, they are actually using TypeScript syntax, including types and everything.
Is this some kind of high-level magic?
Here's an image of VS Code showing errors
You can stick types to JavaScript code, that's named "TypeScript Type Declaration", and the extension is .d.ts. When TypeScript (or also an editor with intellisense) sees a javascript file and a .d.ts file with the same name, it will import the type definitions from that file.
There's a project that aims to provide type definitions for every JavaScript library, maybe you've heard talking about DefinitelyTyped.
For example:
// example.js
function hello(name) {
console.log(`Hello ${name}!`);
}
// example.d.ts
function hello(name: string);
// main.ts
import { hello } from 'example';
hello(42); // Error! "name" must be a string
The same system has been used to provide types in React
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With