love

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

  •  
  •   love · Jan 20, 2021 · 2132 views
    This topic created in 1945 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   ·   5696 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 03:22 · PVG 11:22 · LAX 20:22 · JFK 23:22
    ♥ Do have faith in what you're doing.