泛型的使用
定义类,要多一步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Queue<T> { private data = []; push(item: T) { return this.data.push(item) } pop(): T { return this.data.shift() } }
const queue = new Queue<number>() queue.push(1) console.log(queue.pop().toFixed())
const queue2 = new Queue<string>() queue2.push('str') console.log(queue2.pop().length)
|
定义接口,要多一步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| interface KeyPair<T, U> { key: T; value: U; } let kp1: KeyPair<number, string> = { key: 123, value: "str" } let kp2: KeyPair<string, number> = { key: 'test', value: 123 }
let arr: number[] = [1, 2, 3] let arrTwo: Array<number> = [1, 2, 3]
interface IPlus<T> { (a: T, b: T) : T } function plus(a: number, b: number): number { return a + b; } function connect(a: string, b: string): string { return a + b } const a: IPlus<number> = plus const b: IPlus<string> = connect
|
声明文件
tsconfig.json 解决ts无法获取声明
1 2 3 4
| { "include": ["**/*"] }
|
DefinitelyTyped github
DefinitelyTyped这个库是集中管理 ts 声明库文件的,
任何如 antDesign 要做声明文件,就要向这个 DefinitelyTyped 中提 PR 审核。
在TypeSearch这里可以查询使用的库是否有声明文件。使用外网访问,不然查询不到。
配置文件
配置文件说明demo一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| { "compilerOptions": { "outDir": "dist", "module": "esnext", "target": "es5", "declaration": "jsx": "react", "moduleResolution":"Node", "allowSyntheticDefaultImports": true, }, "include": [ "src" ], "exclude": [ "src/**/*.test.tsx", "src/**/*.stories.tsx", "src/setupTests.ts", ] }
|
tsconfig.json 技巧:去除定义 any的报错
有些项目,如果不定义类型,就会报错ts,此时如果定义 "noImplicitAny": "false"
就可以不用定义any,ts也不会报错了。
1 2 3 4 5 6
| { "compilerOptions": { "noImplicitAny": "false", }, }
|
tsconfig.json 技巧:使用import
1 2 3 4 5 6 7
| { "compilerOptions": { "moduleResolution":"Node", "resolveJsonModule": true, }, }
|