V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
usedtobe
V2EX  ›  问与答

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

  •  1
     
  •   usedtobe · Apr 1, 2021 · 1789 views
    This topic created in 1862 days ago, the information mentioned may be changed or developed.

    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 replies    2021-04-02 01:00:39 +08:00
    B3C933r4qRb1HyrL
        1
    B3C933r4qRb1HyrL  
       Apr 1, 2021
    interface IType {
    a: number;
    b: number;
    c: number;
    }

    这样?
    codehz
        2
    codehz  
       Apr 1, 2021   ❤️ 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>'.
    B3C933r4qRb1HyrL
        3
    B3C933r4qRb1HyrL  
       Apr 1, 2021
    @codehz 应该是你这样...我没看入参...
    codehz
        6
    codehz  
       Apr 2, 2021
    @noe132 不是很懂,<T extends string>(input: T[]): Record<T, number>能解决的事情为啥要玩类型体操
    noe132
        7
    noe132  
       Apr 2, 2021
    @codehz 以为他要连值的类型也要一起有。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3323 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 12:53 · PVG 20:53 · LAX 05:53 · JFK 08:53
    ♥ Do have faith in what you're doing.