Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is React source code written in JavaScript instead of TypeScript, but still has types?

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

like image 846
ff_lol Avatar asked Mar 18 '26 13:03

ff_lol


1 Answers

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

like image 87
Cristian Traìna Avatar answered Mar 20 '26 01:03

Cristian Traìna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!