简体   繁体   English

当我从 Typescript 中的 NPM package 导入类型时,它来自哪个文件?

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

Eg when I do:例如,当我这样做时:

import type React from 'react';

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

Where does React.PropsWithChildren come from? React.PropsWithChildren来自哪里? It's not in React's Github repo and it's not in node_modules/react .它不在 React 的 Github repo 中,也不在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 .我对 DefinitiveTyped 的工作原理了解有限,但没有node_modules/@types/react文件夹,而且我从未安装过@types/react

How is Typescript able to resolve this? Typescript 如何解决这个问题?

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. Javascript解析系统递归查找node_modules文件夹,意思是先看你的代码所在的目录,如果没有找到,再看上层目录,以此类推。

In your case, chances are you have installed the @types/react somewhere in upper directories or even globally. 在您的情况下,您可能已经在上层目录甚至全局的某个位置安装了 @types/react

As @AluanHaddad correctly mentioned, apparently Typescript doesn't fallback to globally installed type packages.正如@AluanHaddad 正确提到的那样,显然 Typescript 不会回退到全局安装的类型包。 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:在 VSCode BTW 中有一个缓存机制( Automatic Type Acquisition ),当它在你的目录node_modules中找不到类型时,它会在以下目录中查找类型:

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

if not found, it then proceed to download the missing types from DefinitelyTyped and put them in aforementioned directories.如果没有找到,它会继续从DefiniteTyped下载丢失的类型并将它们放在上述目录中。

I think you want to know how TypeScript resolve PropsWithChildren .我想你想知道 TypeScript 如何解决PropsWithChildren But you said you didn't install @types/react .但是你说你没有安装@types/react I think in this situation the TypeScript compiler can't resolve this.我认为在这种情况下 TypeScript 编译器无法解决这个问题。

If you want to use TypeScript with React first install @types/react如果你想使用 TypeScript 和 React 首先安装@types/react

Foo.tsx Foo.tsx

import React from 'react';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM