declare
1 2
| declare let $: JQuery; $()....
|
在 TypeScript 中,declare
关键字用于声明全局变量、函数、类或模块的类型,告诉编译器这些实体已经存在,不需要进行编译时的类型检查。
declare
关键字通常用于以下情况:
- 声明全局变量:
1
| declare const myGlobalVariable: string;
|
上述代码告诉编译器 myGlobalVariable
是一个全局变量,类型为 string
。
- 声明全局函数:
1
| declare function myGlobalFunction(param: string): void;
|
上述代码告诉编译器 myGlobalFunction
是一个全局函数,接受一个 string
类型的参数,并返回 void
。
- 声明全局类:
1 2 3 4
| declare class MyClass { constructor(name: string); sayHello(): void; }
|
上述代码告诉编译器 MyClass
是一个全局类,具有一个接受 string
类型参数的构造函数和一个 sayHello
方法。
- 声明全局模块:
1 2 3 4
| declare module 'my-module' { export function myModuleFunction(): void; export const myModuleVariable: number; }
|
上述代码告诉编译器 my-module
是一个全局模块,其中包含一个 myModuleFunction
函数和一个 myModuleVariable
变量。
通过使用 declare
关键字,你可以在 TypeScript 中声明全局实体的类型,以便编译器不会对其进行类型检查。这在与第三方库集成或处理一些特殊情况时非常有用。
泛型
1 2 3 4
| function Fn<T(该名字可以随意)>(a:T,b:string):T{ } fn<number>(1,'1');
|
需要多个泛型约束
1 2 3 4
| function Fn<T,P>(a:T,b:string):T{ } fn<number,string>(1,'1');
|
接口也可以使用泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| interface Page{ current:number; size:number; } interface Opt<R> { name:string; page:R } const a:Opt<Page> = { name:'shao.yuhong', page:{ current:1, size:10 } }
|
keyof
1 2 3 4 5 6 7 8 9
| interface IMap { name: string, age: number, sc: string, show: boolean }
type values = keyof IMap;
|
函数属性
1 2 3 4 5 6 7 8
| type Ifunc = { (val: string): string; age: string; } const func1: Ifunc = function () { return '111' } func1.age = '22';
|