V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
usedtobe
V2EX  ›  问与答

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

  •  1
     
  •   usedtobe · 2021-04-01 20:15:22 +08:00 · 1217 次点击
    这是一个创建于 1112 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 三个属性,大家有什么思路吗

    7 条回复    2021-04-02 01:00:39 +08:00
    cuvii
        1
    cuvii  
       2021-04-01 20:35:34 +08:00
    interface IType {
    a: number;
    b: number;
    c: number;
    }

    这样?
    codehz
        2
    codehz  
       2021-04-01 20:38:08 +08:00   ❤️ 3
    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
        3
    cuvii  
       2021-04-01 20:59:06 +08:00
    @codehz 应该是你这样...我没看入参...
    codehz
        6
    codehz  
       2021-04-02 00:31:51 +08:00
    @noe132 不是很懂,<T extends string>(input: T[]): Record<T, number>能解决的事情为啥要玩类型体操
    noe132
        7
    noe132  
       2021-04-02 01:00:39 +08:00
    @codehz 以为他要连值的类型也要一起有。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3710 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:40 · PVG 12:40 · LAX 21:40 · JFK 00:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.