is
is 类型保护,用于判断类型的函数中做类型限制
// bad
function isString(value: unknown): boolean{
return typeof value === "string";
}
//good
function isString(value: unknown): value is string{
return typeof value === "string";
}
in
in 其实就像是遍历一样
type Keys = 'a' | 'b' | 'c';
type obj = {
[ T in Keys]: string;
}
// in 遍历 Keys,并为每个值赋予 string 类型
// type Obj = {
// a: string,
// b: string,
// c: string
// }
keyof
keyof 可以获取一个对象接口的所有 key值
type obj = { a: string; b: string }
type Foo = keyof obj;
// type Foo = 'a' | 'b';
typeof
typeof 用于获取某个变量的具体类型
const obj = { a: '1' };
type Foo = typeof obj;
// type Foo = { a: string }
extends、implements
- extends用于接口与接口、类与类、接口与类之间的继承
- implements用于类与类、类与接口之间的实现
注意: extends类似于es6的extends,implements没有继承效果的,但是要求子类上必须需有父类的属性和方法,更倾向于限制子类的结构!
type、interface
type 类型别名 用于给类型起一个新名字
type Value: string = "111"
// 或
type Iprops = {
value: string,
getName: () => string
}
interface 接口 用于声明类型
interface MyInterface {
value: string,
getName: () => string
}
type 和 interface的区别
- type可以定义单个变量类型、联合类型、对象,interface只能定义对象;
-
type不可以重复声明,interface可以重复声明(声明合并);
type Iprops = { name: string age: number } type Iprops:string = "111" // Error 标识符“Iprops”重复。ts(2300) interface MyInterface { name: string age: number } interface MyInterface { gender: string } const obj: MyInterface= { name: "string" age: 18, gender: "男", } // 重复声明相当于把两个类型加一块