了解:使用类型声明文件给JS文件添加类型
-
在导入 .js 文件时,TS 会自动加载与 .js 同名的 .d.ts 文件,以提供类型声明。
-
declare 关键字:
-
用于类型声明,为其他地方(比如,.js 文件)已存在的变量声明类型,而不是创建一个新的变量。
-
对于
type
interface
等这些明确就是 TS 类型的(只能在 TS 中使用的),可以省略
declare 关键字。 -
其他 JS 变量,应该使用
declare
关键字,明确指定此处用于类型声明。
-
add/index.js
const add = (a, b) => {
return a + b;
};
const ponit = (p) => {
console.log('坐标:', p.x, p.y);
};
export { add, ponit }
add/index.d.ts
declare const add: (a: number, b: number) => number;
type Position = {
x: number;
y: number;
};
declare const ponit: (p: Position) => void;
export { add , ponit};
main.ts
import { add , ponit} from './add';
add(3, 10)
ponit({x: 100, y: 200})