1. d.ts 文件之间引用版本不匹配问题:
例如
antd d.ts 是 "antd": "^1.11.6", ie 8 兼容版本
react d.ts 是 "@types/react": "^0.14.57", 该版本是typescript 2.0
tsc 编译错误
error TS2314: Generic type 'FormEventHandler' requires 1 type argument(s).
error TS7006: Parameter 'index' implicitly has an 'any' type.
error TS7031: Binding element 'TreeNode' implicitly has an 'any' type.
解决方法:
{
"compilerOptions": {
"skipLibCheck": true
}
}
2. d.ts 文件缺失某个interface 属性
例如:antd d.ts 文件 interface InputProps {} 中 缺失 onPressEnter 属性,你的应用使用该属性是报错
error TS2339: Property 'onPressEnter' does not exist on type 'IntrinsicAttributes & Int
rinsicClassAttributes<Input> & { children?: ReactNode; } & InputProps'.
解决方法:
设置多个定义typescript 定义文件源
{
"compilerOptions": {
"typeRoots" : ["./Scripts/@typings/","./node_modules/@types/"],
}
}
添加补全 interface 中缺失的属性:
import * as React from 'react'
declare module "antd" {
interface TreeNodeProps {
dataRef?: any
}
interface InputProps {
onPressEnter?: any;
rows?:number;
}
}
注意 一定要定义 declare module “antd” 将标识为外部模块,
这个是为了 import ... from "antd",从外部模块模块与 node_modules/antd/index.d.ts 读取,然后typescript 将连个文件interface 可以合并 。
import 读取方式 https://www.tslang.cn/docs/handbook/namespaces-and-modules.html
3. 方法形式参数与返回值取消类型检查
从 javascript 转到 typescript 不是适应在函数参数加类型定义
解决方法tsconfig 配置 false
"compilerOptions": {
"target": "es3",
"noImplicitAny": false, //fasle 默认类型any
}
如果函数返回值加类型
typescript 可以更加return 值进行类型推断。
如下
export class Observable<T> {
// ... implementation left as an exercise for the reader ...
}
declare global {
interface Array<T> {
toObservable(): Observable<T>;
}
}
Array.prototype.toObservable = function () {
return new Observable();
}
参考资料
https://github.com/OfficeDev/office-ui-fabric-react/issues/382
https://justintimecoder.com/how-to-polyfil-missing-types-in-typescript/