选择函数在打字稿中接受字符串或数组

我想用打字稿写这个函数:


const pick = (obj, keys) => {

  if (!Array.isArray(keys)) keys = keys.split(',')

  return keys.reduce((acum, key) => (acum[key] = obj[key], acum), {})

}


const o = {

  a: 1,

  b: 2,

  c: 3

}


console.log('o[a,c]:', pick(o, 'a,c'))        // { a: 1, c: 3 }

console.log('o[a,c]:', pick(o, ['a', 'c']))   // { a: 1, c: 3 }

我已经看到这个答案,这似乎是一个很好的起点,但我不知道如何将字符串转换为 K[]。


或者我可以以某种方式告诉 Typescript 相信我,并且不要检查类型吗?


沧海一幻觉
浏览 166回答 2
2回答

ibeautiful

打字稿编译器不知道当您使用拆分评估字符串时您的字符串将是什么,因此您必须强制K[]使用它,这将返回T.根据您所需的用途,只有第二个才能获得所需的类型。// i changed the "a" property to a stringconst 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> => {&nbsp; &nbsp; 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.&nbsp; &nbsp; 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 objlet p2 = pick(o, ['a','c']); // { a: string , c: number }

红糖糍粑

你可以使用联合const pick = (obj: Object,&nbsp; keys: string[] | string) => {....}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript