Typescript 定义文件问题汇总

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/

转载于:https://my.oschina.net/fsilence/blog/1577121

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值