V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
love
V2EX  ›  TypeScript

Typescript 的泛型参数必须要么不填要么填完整?这种情况怎么处理?

  •  
  •   love · 2021-01-20 19:18:11 +08:00 · 1437 次点击
    这是一个创建于 1163 天前的主题,其中的信息可能已经有所发展或是发生改变。
    class Model {
        a!: number
        b!: string
    }
    
    class ModelB extends Model {
        c!: boolean
    }
    
    declare function getData<R, M extends Model>(m: M, field: keyof M): R
    
    // 这里我希望 M 参数自动取自第一个参数,然后可以指定一个返回值类型为 number 。
    // 可是似乎做不到?报缺一个泛型参数错误
    let r = getData<number>(new ModelB(), 'c')
    

    Playground

    codehz
        1
    codehz  
       2021-01-20 19:29:03 +08:00   ❤️ 1
    youmoo
        2
    youmoo  
       2021-04-16 18:09:32 +08:00
    其实你可以这样调用:

    let r: number = getData(new ModelB(), 'c');
    love
        3
    love  
    OP
       2021-04-17 16:35:14 +08:00
    @youmoo 这似乎只是把类型换了个位置,还是要写的啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5906 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 02:10 · PVG 10:10 · LAX 19:10 · JFK 22:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.