为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

沧海一幻觉 2021-06-30 05:15:47
我想用打字稿写这个函数: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 相信我,并且不要检查类型吗?
查看完整描述

2 回答

?
ibeautiful

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 }


查看完整回答
反对 回复 2021-07-01
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

你可以使用联合


const pick = (obj: Object,  keys: string[] | string) => {

....

}


查看完整回答
反对 回复 2021-07-01
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信