有没有一种方法可以创建一个需要对象所有键的类型



这是我的代码:

interface Props {
id: string;
name: string;
age: number;
};
const keysOfProps: (keyof Props)[] = ['id', 'name']; // This should show a warning because the ``age`` string is missing

我希望此keyOfProps的类型为['id, 'name', 'age'],而不是('id' | 'name' | 'age')[]

我怎样才能做到这一点?

虽然不可能为元组定义所需的类型,但可以断言给定元组的类型与所有键匹配。我们可以使用Pick实用程序类型的变体来从Props构建一个类型,该类型包含元组定义的键,然后我们可以断言结果与原始Props相同。该解决方案需要几个步骤和一个函数调用,但以下内容应该有效:

type Tuple<T> = readonly T[]
type TuplePick<T, K extends Tuple<keyof T>> = Pick<T, K[number]> // like Pick, but we pass a tuple of the keys
type IfEqualThen<T, U, R> = T extends U ? (U extends T ? R : never) : never // 'R' if T and U are mutually assignable
type AssertAllKeys<P, T extends Tuple<keyof P>> = IfEqualThen<P, TuplePick<P, T>, T>
function assertKeys <P> () {
return function <T extends Tuple<keyof P>> (value: AssertAllKeys<P, T>): T 
{
return value
}
}
interface Props {
id: string;
name: string;
age: number;
};
const keys1 = assertKeys<Props>()(['id', 'name'] as const) // Error, argument not assignable to never
const keys2 = assertKeys<Props>()(['id', 'name', 'age'] as const) // Works

最新更新