【发布时间】:2018-04-09 13:38:04
【问题描述】:
Typescript 允许您为本地 javascript 文件编写 .d.ts 定义文件,如下所示:
src/
main.js
imported.js
imported.d.ts
main.js
import { func } from './imported';
console.log(func("1", "1"));
imported.js
export const func = (numVal, strVal) =>
`The number is ${numVal}, the string is ${strVal}`;
imported.d.ts
export const func: (numVal: number, strVal: string) => string;
这会产生以下错误,带有选项noImplicitAny:
src/imported.js(1,22): error TS7006: Parameter 'numVal' implicitly has an 'any' type.
src/imported.js(1,30): error TS7006: Parameter 'strVal' implicitly has an 'any' type.
src/main.js(3,18): error TS2345: Argument of type '"1"' is not assignable to parameter of type 'number'.
最后一个错误很好,当我们应该传递一个数字作为第一个参数时,它阻止了我们传递一个字符串。但是对于前两个,在导入的 javascript 文件中,它不知道参数的类型已经定义。这会阻止您使用 noImplicitAny,但也会阻止您在例如将 numValue 传递给需要字符串的函数时出错。
是否可以让 javascript 文件知道它们在 typescript 中的定义,最好不修改原始 javascript。
【问题讨论】:
-
一般 .d.ts 文件仅用于为您无法控制的文件提供定义,例如外部模块的接口。您不能使用它为项目中的源代码创建并行定义。换句话说,在解释 JS 文件 (
imported.js) 时,它忽略了定义。这真的不应该是要走的路。你应该有一个导入的.ts 文件并将其用于实现和定义。
标签: javascript typescript .d.ts