Typescript如何获取类型的可选键

Kir*_*l A 5 typescript

有一种类型

{ a: string, b: number, c?: string, d?: number }
Run Code Online (Sandbox Code Playgroud)

如何获取类型

'c' | 'd'
Run Code Online (Sandbox Code Playgroud)

由此?

Kir*_*l A 6

最后我找到了基于Typescript的解决方案如何创建具有两种类型的共同属性的类型?

type MappedC<A, B> = {
  [K in keyof A & keyof B]:
  A[K] extends B[K]
    ? never
    : K
};

type OptionalKeys<T> = MappedC<T, Required<T>>[keyof T];
Run Code Online (Sandbox Code Playgroud)

但它的工作原理就像一个魔术,因为当将这两种类型合并为一种并将 B 替换为必需时,它就会停止工作。

其他解决方案,似乎更稳定:

export type KeysOfType<T, U> = { [K in keyof T]: T[K] extends U ? K : never }[keyof T];
export type RequiredKeys<T> = Exclude<KeysOfType<T, Exclude<T[keyof T], undefined>>, undefined>;
export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
Run Code Online (Sandbox Code Playgroud)

  • 这些实际上是不同的解决方案。举个例子: ```ts type Foo = { a: string; b: 字符串 | 不明确的; c?: 字符串 }; ``` 前一个解决方案(基于 `Mapped`)将返回(预期的):`'c'`。后一个解决方案(基于“RequiredKeys”)将返回(意外的):“b” | 'c'`。 (3认同)