2 回答

TA贡献1993条经验 获得超5个赞
打字稿编译器不知道当您使用拆分评估字符串时您的字符串将是什么,因此您必须强制K[]使用它,这将返回T.
根据您所需的用途,只有第二个才能获得所需的类型。
// i changed the "a" property to a string
const o = { a: 'hello', b: 2, c: 3 };
// <T, K extends keyof T> - here you assign the generics
// T - will be used on "obj" parameter so it can inherit it's properties
// K - will be a property of T
// I typed the "keys" parameter with "string" (to respect your first usage) and K[] (an array of K properties , for the second one)
// At last, we want the function to return K props of T, we have the Pick construct for that.
const pick = <T, K extends keyof T>(obj: T, keys: string | K[]): Pick<T, K> => {
if (!Array.isArray(keys)) keys = (keys as string).split(',') as K[]; // we know that "keys" is a string, so we'll force the type on it, and we'll force K[] on the .split result, this will return all types from T.
return keys.reduce((acum, key: K) => (acum[key] = obj[key], acum), {} as T ); // here we mark the accumulator as T, so we know what properties are used.
};
let p1 = pick(o, 'a,c'); // { a: string , b: number, c: number } - You'll get all the keys from obj
let p2 = pick(o, ['a','c']); // { a: string , c: number }
添加回答
举报