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

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

  •  
  •   love · Jan 20, 2021 · 2093 views
    This topic created in 1932 days ago, the information mentioned may be changed or developed.
    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  
       Jan 20, 2021   ❤️ 1
    youmoo
        2
    youmoo  
       Apr 16, 2021
    其实你可以这样调用:

    let r: number = getData(new ModelB(), 'c');
    love
        3
    love  
    OP
       Apr 17, 2021
    @youmoo 这似乎只是把类型换了个位置,还是要写的啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5488 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 05:57 · PVG 13:57 · LAX 22:57 · JFK 01:57
    ♥ Do have faith in what you're doing.