Leo Jiang
Leo Jiang

Reputation: 26085

When I import a type from an NPM package in Typescript, which file is it coming from?

E.g. when I do:

import type React from 'react';

function Foo({ children }: React.PropsWithChildren<{}>);

Where does React.PropsWithChildren come from? It's not in React's Github repo and it's not in node_modules/react. I have a limited understanding of how DefinitelyTyped works, but there isn't a node_modules/@types/react folder and I never installed @types/react.

How is Typescript able to resolve this?

Upvotes: 3

Views: 612

Answers (2)

Mahdi Ghajary
Mahdi Ghajary

Reputation: 3253

Javascript resolving system recursively look for node_modules folders, it means it first look at the directory that your code is in, if not found, then the upper directory and so on.

In your case, chances are you have installed the @types/react somewhere in upper directories or even globally.

As @AluanHaddad correctly mentioned, apparently Typescript doesn't fallback to globally installed type packages. in VSCode BTW there's a caching mechanism (Automatic Type Acquisition), whenever it can't find the types in your directory node_modules, it then look for the types in below directories:

  • Mac: ~/Library/Caches/TypeScript
  • Windows: %LOCALAPPDATA%\Microsoft\TypeScript
  • Linux: ~/.cache/typescript/

if not found, it then proceed to download the missing types from DefinitelyTyped and put them in aforementioned directories.

Upvotes: 2

Stark Jeon
Stark Jeon

Reputation: 1145

I think you want to know how TypeScript resolve PropsWithChildren. But you said you didn't install @types/react. I think in this situation the TypeScript compiler can't resolve this.

If you want to use TypeScript with React first install @types/react

Foo.tsx

import React from 'react';

function Foo({ children }: React.PropsWithChildren<{}>);

Upvotes: 0

Related Questions