在条件块中使用 typeof,instanceof,in,字面量类型,TypeScript 将会推导出在条件块中的变量类型。
// typeof 示例let str = '123';if (typeof str === 'string') {str.substr(1)}// instanceof 示例class Foo {name!: string;play!: Function;}let foo = <Foo>{ name: 'Alex' }if (foo instanceof Foo) {foo.play()}// in 示例type Name = {name: string;}type Age = {age: number;}function isNameOrAge (q: Name | Age) {if ('name' in q) {q.name} else {q.age}}// 字面量类型保护type Bar1 = {kind: 'bar';name: string;}type Foo1 = {kind: 'foo';age: number;}function isBar1OrFoo1 (q: Bar1 | Foo1) {if (q.kind === 'bar') {q.name} else {q.age}}
自定义类型保护
type Name = {name: string}type Age = {age: number}function isName (val: Name | Age): val is Name {return (val as Name).name !== undefined;}function isNameOrAge (q: Name | Age) {if (isName(q)) {q.name} else {q.age}}
