Skip to content

类型保护

通过 typeof、instanceof、in、is 具体到某个类型

ts
const foo = (v: string | number) {
  if (typeof v === 'string') {

  } else {

  }
}

class Foo {
  foo () {} 
}

class Bar {
  bar () {}
}

const getIns = (cls: new() => Foo | Bar) => {
  return new cls
}

const ins = getIns(Foo)
if (ins instance of Foo) {
  ins.foo
} else {
  ins.bar
}

if ('foo' in Foo) {

} else {

}

TS 特有的可辨识类型

ts
interface Foo {
  name: 'foo' // 字面量类型
}
interface Bar {
  name: 'bar'
}

const fn = (v: Foo | Bar) => {
  if (v.name === 'foo') {

  } else {

  }
}
ts
const isString (v: unknown): v is string => {
  return typeof v === 'string'
}
const isFoo (cls: Foo | Bar): cls is Foo => {
  return 'foo' in Foo
}

null 保护

ts
const foo (v?: number | null) => {
  // v?.toFixed()
  // v!.toFixed()
  // v && v.toFixed()

  v = v || 10
  const bar () {
    v.toFixed() // Error,TS 无法检测函数内部变量,需要再次判断。
    
    if (v != null) {
      v.toFixed() // OK
    }
  }

  bar()
}