typescript 函数类型为空检查

残北

关注

阅读 57

2022-03-19

type NonNull = string | number | null | undefined

// 使用关键字 NonNullable 来将类型包含起来,就能有效的将 type 类型中的 null 跟 undefined 剔除
function showType(args: NonNullable<NonNull>) {
  console.log(args);
}

 此时调用函数时,参数类型提示只能是 string | number 类型

// 定义类型 K 是 T 中的属性 将其属性的所有类型定义为 string
type StringMap<T> = {
  [K in keyof T]:string
}

function showType(args: StringMap<{ id: number, name: string }>) {
  console.log(args);
}

showType({id:12,name:'张全祥'})

 此时的 id 只能传 string 类型了

精彩评论(0)

0 0 举报