如何获取类型的必需键的字符串联合

时间:2019-04-15 16:32:42

标签: typescript

我想建立一个所有类型的必需键的字符串联合。 示例:

interface IPerson {
    readonly name: string;
    age?: number;
    weight: number;
}

RequiredKeys<IPerson>  // a type returning "name" | "weight"
ReadonlyKeys<IPerson>  // a type returning "name"

我不知道如何过滤可选(或只读)键

2 个答案:

答案 0 :(得分:1)

TypeScript尚无内置方法来提取可选内容。

interface IPerson {
  readonly name: string;
  age?: number;
  weight: number;
}

// First get the optional keys
type Optional<T> = {
  [K in keyof T]-?: ({} extends { [P in K]: T[K] } ? K : never)
}[keyof T];

// Use the pick to select them from the rest of the interface
const optionalPerson: Pick<IPerson, Optional<IPerson>> = {
  age: 2
};

答案 1 :(得分:0)

感谢@ ali-habibzadeh

type RequiredKeys<T> = {
  [K in keyof T]-?: ({} extends { [P in K]: T[K] } ? never : K)
}[keyof T];

type OptionalKeys<T> = {
  [K in keyof T]-?: ({} extends { [P in K]: T[K] } ? K : never)
}[keyof T];