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

问题描述 投票:1回答:2

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

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

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

我无法弄清楚如何过滤掉可选(或只读)键

typescript
2个回答
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
};

0
投票

Thaks @ 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];

要获得只读/可写的密钥,您可以使用:Details

type IfEquals<X, Y, A=X, B=never> =
  (<T>() => T extends X ? 1 : 2) extends
  (<T>() => T extends Y ? 1 : 2) ? A : B;

type WritableKeys<T> = {
  [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
}[keyof T];

type ReadonlyKeys<T> = {
  [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, never, P>
}[keyof T];
© www.soinside.com 2019 - 2024. All rights reserved.