类型查询操作符

  • typeof:用于基本类型

类型守卫

is

  • is 关键字 + 预期类型。如果这个函数成功返回为 true,那么 is 关键字前这个入参的类型,就会被这个类型守卫调用,方便后续的类型控制流分析
function isString(input: unknown): input is string {
return typeof input === "string";
}

function foo(input: string | number) {
if (isString(input)) {
// 正确了
(input).replace("linbudu", "linbudu599")
}
if (typeof input === 'number') { }
// ...
}

in

  • 通过 key in object 的方式来判断 key 是否存在于 object 或其原型链上(返回 true 说明存在)。
interface Foo {
foo: string;
fooOnly: boolean;
shared: number;
}

interface Bar {
bar: string;
barOnly: boolean;
shared: number;
}

function handle(input: Foo | Bar) {
if ('foo' in input) {
input.fooOnly;
} else {
input.barOnly;
}
}

instanceof

  • 类似于 typeof 与 in 的操作符,用于引用类型,包括判断A是否是B的实例
class FooBase {}

class BarBase {}

class Foo extends FooBase {
fooOnly() {}
}
class Bar extends BarBase {
barOnly() {}
}

function handle(input: Foo | Bar) {
if (input instanceof FooBase) {
input.fooOnly();
} else {
input.barOnly();
}
}

类型断言守卫asserts

  • 断言守卫和类型守卫最大的不同点在于,在判断条件不通过时,断言守卫需要抛出一个错误,类型守卫只需要剔除掉预期的类型。
function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new Error(msg);
}
}

接口合并

  • 继承extends

  • 接口合并,这些同名属性的类型仍然需要兼容

interface Struct1 {
primitiveProp: string;
objectProp: {
name: string;
};
unionProp: string | number;
}

// 接口“Struct2”错误扩展接口“Struct1”。
interface Struct2 extends Struct1 {
// “primitiveProp”的类型不兼容。不能将类型“number”分配给类型“string”。
primitiveProp: number;
// 属性“objectProp”的类型不兼容。
objectProp: {
age: number;
};
// 属性“unionProp”的类型不兼容。
// 不能将类型“boolean”分配给类型“string | number”。
unionProp: boolean;
}