【发布时间】:2020-05-13 00:52:23
【问题描述】:
选择功能的书写类型有问题。当只选择一个键或几个具有相同类型值的键时,一切正常。但是如果我试图选择几个键并且它们的值是不同的类型 - 我会得到一个错误。不太清楚我在哪里做错了。
感谢您的宝贵时间。
export interface Mapper<T = any, R = any> {
(arg: T): R;
}
export function pick<O, T extends keyof O>(keys: T[], obj?: O): { [K in T]: O[T] };
export function pick<T>(keys: T[], obj?: never): Mapper;
export function pick<O, T extends keyof O>(keys: T[], obj?: O) {
const picker: Mapper<O, { [K in T]: O[T] }> = _obj =>
keys.reduce((acc, key) => {
if (key in _obj) {
acc[key] = _obj[key];
}
return acc;
}, {} as O);
return obj ? picker(obj) : picker;
}
const obj = { someKey: 'value', otherKey: 42, moreKey: ['array value'] };
const newObj = pick(['otherKey'], obj);
//OK. TS type for newObj is {otherKey: number}
const n: number = newObj.otherKey;
// OK
const otherNewObj = pick(['otherKey', 'someKey'], obj);
//no really OK. TS type for otherNewObj is {otherKey: number | string, someKey: number | string}
const m: number = otherNewObj.someKey;
// Error. Type string | number is not assignable to the number
【问题讨论】:
标签: javascript typescript types generic-type-argument