首先要介绍的是Type Guard,Type Guard 顾名思义就是类型的看守者,刚刚 TypeScript 会报错就是因为 type 不一样,所以只要我们建立一个类型的看守者,让 TypeScript 知道这个变量一定会符合我enum中的某一个value时,这时候就不会出现红字了,而通常 Type Guard 会写成一个function像这样: 代码语言:javascript 代码运...
} isFlat function return value is a boolean value. We add 'array is T[]' that adds additional information for types. isFlat(numbers): numbers type is '(number|number())[]' but inside if statement: numbers is 'number[]', because we tell typescript, array is T[] in the return valu...
类型守卫函数(Type Guard Function) 类型守卫函数写法如下。 type Fish = { swim: () => void }; type Bird = { fly: () => void }; declare const pet: Fish | Bird; function isFish(pet: Fish | Bird): pet is Fish { return 'swim' in pet; } if (isFish(pet)) { // pet类型被收敛...
class Foo {} class Bar {} function test(input: Foo | Bar) { if (input instanceof Foo) { // 这里 input 的类型「收紧」为 Foo } else { // 这里 input 的类型「收紧」为 Bar } } 属性判断:in interface Foo { foo: string; } interface Bar { bar: string; } function test(input: ...
Type Guard 首先要介绍的是 Type Guard,Type Guard 顾名思义就是类型的看守者,刚刚 TypeScript 会报错就是因为 type 不一样,所以只要我们建立一个类型的看守者,让 TypeScript 知道这个变量一定会符合我 enum 中的某一个 value 时,这时候就不会出现红字了,而通常 Type Guard 会写成一个 function 像这样: ...
type guard:type 守护。当遇到一个联合类型的时候,使用这个条件语句,可以自动帮你缩小这个类型的范围,最常见的关键字是:typeof // 通过条件来智能缩小范围,if 是 string 类型,那么 else 就是 number 类型 function getLength (input: string | number): number { ...
-4--函数 Function: Interface描述函数: -5--类型推论 -6--联合类型 -7--类型断言 as: type guard: -8--枚举(Enum) 常量枚举: -9--泛型: 箭头函数的泛型: 约束泛型: -10--泛型在类和接口中使用: 类中: 接口中: -11--类型别名 字面量 交叉类型 ...
interfaceCarLike{make:stringmodel:stringyear:number}letmaybeCar:unknown// the guardfunctionassertsIsCarLike(valueToTest:any):asserts valueToTest is CarLike{if(!(valueToTest&&typeofvalueToTest==="object"&&"make"invalueToTest&&typeofvalueToTest["make"]==="string"&&"model"invalueToTest&&typeof...
functionfunc(value:unknown){// @ts-ignore: Object is of type 'unknown'.value.length;if(typeofvalue==='string'){// type guard// %inferred-type: stringvalue;value.length;// OK}} 代码语言:javascript 代码运行次数:0 运行 AI代码解释
使用类型区分(Type Guard)可以根据条件判断不同的类型。以下是常见的类型区分方法: instanceof操作符 使用instanceof操作符可以判断一个对象是否为指定类的实例。例如: 代码语言:typescript AI代码解释 classA{}classB{}functionprocess(obj:A|B){if(objinstanceofA){console.log('This is an instance of A');...