我有一个预定义的复杂接口,我不能操纵它,因为它来自第三方库.
interface Fruit {
name?: string;
id?: number;
weight?: number;
}
我需要
- 定义该接口的键的子集的列表,然后
- 定义一个新接口(或类型),它将只包含那些^成员,其类型将与原始接口相同.
To clarify: 我需要 actually use the list in my code (otherwise I would just write them into a Pick<Fruit, ...>
and be done with it).
以下是一种方法:
const fieldsToIsolate = ["id", "weight"] as const;
type IsolatedFruit = Pick<Fruit, typeof fieldsToIsolate[number]>;
// type IsolatedFruit = {
// id?: number | undefined;
// weight?: number | undefined;
// }
这种方法的问题是fieldsToIsolate
不是类型安全的.
这里有一个不同的方法可以解决这个问题,但有自己的问题:
const fieldsToIsolate: Array<keyof Fruit> = ["id", "weight"];
type IsolatedFruit = Pick<Fruit, typeof fieldsToIsolate[number]>;
// type IsolatedFruit = {
// name?: string | undefined;
// id?: number | undefined;
// weight?: number | undefined;
// }
现在,名单已经安全地输入了,但IsolatedFruit
并不准确.
如果我们try 重新附加as const
,则TypeScrip现在会出现问题,因为
The type 'readonly ["id", "weight"]' is 'readonly' and cannot be assigned to the mutable type '(keyof Fruit)[]'
有没有办法实现这一点?