求助,请教一个 Typescript 类型写法问题

2021-04-01 20:15:22 +08:00
 usedtobe

ts 小白,初次学习 ts,想实现一个函数,传入一个字符串数组,返回一个以这个数组里的元素作为 key 的对象

function fn (array: string[]): ReturnType {}

比如传入 ['a', 'b', 'c'],会返回 {'a': 1, 'b': 2, 'c': 3}

现在卡在了这个 ReturnType 类型要怎么写上面。。。

一种思路是

interface ReturnType { [key: string]: number }

但是这样提示不够精确,想让 ts 能够提示出返回值包含 a,b,c 三个属性,大家有什么思路吗

1233 次点击
所在节点    问与答
7 条回复
cuvii
2021-04-01 20:35:34 +08:00
interface IType {
a: number;
b: number;
c: number;
}

这样?
codehz
2021-04-01 20:38:08 +08:00
declare function fn<T extends string>(input: T[]): Record<T, number>;

const ret = fn(['a', 'b']);
ret.a = 1;
ret.b = 2;
ret.c = 3; // error: Property 'c' does not exist on type 'Record<"a" | "b", number>'.
cuvii
2021-04-01 20:59:06 +08:00
@codehz 应该是你这样...我没看入参...
noe132
2021-04-01 21:47:50 +08:00
noe132
2021-04-01 21:52:54 +08:00
codehz
2021-04-02 00:31:51 +08:00
@noe132 不是很懂,<T extends string>(input: T[]): Record<T, number>能解决的事情为啥要玩类型体操
noe132
2021-04-02 01:00:39 +08:00
@codehz 以为他要连值的类型也要一起有。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/767333

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX