logoProsperBao

IsRequiredKey

2022-05-26 01

题目来源(type-challenges)

问题

type case1 = IsRequiredKey<{ a: number; b?: string }, 'a'> // true
type case2 = IsRequiredKey<{ a: number; b?: string }, 'b'> // false
type case3 = IsRequiredKey<{ a: number; b?: string }, 'b' | 'a'> // false

解答

type IsRequiredKey<T, K extends keyof T> = Record<K, T[K]> extends T ? true : false

拆分

  • keyof T 会过只拿出允许访问的属性
  • 利用 Record<K, T[K]> 构造一个参数必选的对象
  • 再判断构造的对象是否是 T 的子集