Typescript 如何获取类型所需键的字符串并集

Typescript 如何获取类型所需键的字符串并集,typescript,Typescript,我想构建一个类型的所有必需键的字符串联合。 例如: interface-IPerson{ 只读名称:字符串; 年龄:数字; 重量:个数; } RequiredKeys//返回“name”|“weight”的类型 ReadonlyKeys//返回“name”的类型 我不知道如何过滤出可选(或只读)键。TypeScript还没有一个内置的方法来提取可选项 interface IPerson { readonly name: string; age?: number; weight: n

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

interface-IPerson{
只读名称:字符串;
年龄:数字;
重量:个数;
}
RequiredKeys//返回“name”|“weight”的类型
ReadonlyKeys//返回“name”的类型

我不知道如何过滤出可选(或只读)键。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
};
interface-IPerson{
只读名称:字符串;
年龄:数字;
重量:个数;
}
//首先,获取可选密钥
类型可选={
[K-in-keyof T]-?:({}扩展了{[P-in-K]:T[K]}?K:never)
}[keyof T];
//使用“拾取”从界面的其余部分中选择它们
const optionalPerson:选择={
年龄:2
};
谢谢@ali habibzadeh

type RequiredKeys={
[K in keyof T]-?:({}扩展了{[P in K]:T[K]}?从不:K)
}[keyof T];
键入可选键={
[K-in-keyof T]-?:({}扩展了{[P-in-K]:T[K]}?K:never)
}[keyof T];
要获取只读/可写密钥,可以使用:

IfEquals类型=
(()=>T扩展X?1:2)扩展
(()=>T扩展Y?1:2)?A:B;
类型可写键={
[P in keyof T]-?:如果等于
}[keyof T];
类型ReadonlyKeys={
[P in keyof T]-?:如果等于
}[keyof T];