ff_lol
ff_lol

Reputation: 129

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

Upvotes: 12

Views: 2345

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122052

React source code is written in Flow. The file extension is still .js, and there are types in those files. If Flow isn't installed, VS Code doesn't understand what it is and just reports a bunch of bugs.

Upvotes: 1

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10414

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

Upvotes: 2

Related Questions