我有一个预定义的复杂接口,由于它来自第三方库,我无法操作它。
interface Fruit {
name?: string;
id?: number;
weight?: number;
}
我需要
-
定义该接口的键子集的列表,然后
-
定义一个只有^个成员的新接口(或类型),该接口的类型与原始接口相同。
澄清一下:我需要在代码中实际使用列表(否则我只会把它们写进
Pick<Fruit, ...>
并就此结束)。
以下是一种方法:
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
不准确。
如果我们尝试重新连接,Typescript现在会抱怨
as const
因为
The type 'readonly ["id", "weight"]' is 'readonly' and cannot be assigned to the mutable type '(keyof Fruit)[]'
有办法做到这一点吗?