【发布时间】:2020-09-14 23:30:06
【问题描述】:
目前我有以下types:
type PossibleKeys = number | string | symbol;
type ValueOf<T extends object> = T[keyof T];
type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>>> =
Omit<T, keyof U> & { [P in ValueOf<U>]: T[keyof U] };
...但是,虽然它甚至可以部分工作,但它给出了以下错误:
类型 'U[keyof U]' 不能分配给类型 'string |号码 | 符号'。
interface Item {
readonly description: string;
readonly id: string;
}
interface MyInterface {
readonly id: string;
readonly propToReplace: number;
readonly anotherPropToReplace: readonly Item[];
}
type ReplacedUser = ReplaceKeys<MyInterface, { propToReplace: 'total', anotherPropToReplace: 'items' }>;
在ReplacedUser 我可以看到类型几乎是正确的。推断类型为:
{ id: string; total: number | readonly Item[]; items: number | readonly Item[]; }
...在我期待的时候:
{ id: string; total: number; items: readonly Item[]; }
我做错了什么?我首先想知道如何表达P 需要获取U 中传递的值 以抑制Typescript 错误,然后获取特定value 的正确类型。
【问题讨论】:
标签: typescript typescript-generics