Constraints on interface members in typescript generics

后端 未结 3 1255
Happy的楠姐
Happy的楠姐 2021-01-14 00:17

I have a method, that should accepts any object, as long as all its fields are strings or numbers

I made this, which works great with duck typing

sta         


        
3条回答
  •  盖世英雄少女心
    2021-01-14 00:52

    T's constraint can refer to T (with some restrictions), so you can use a mapped type to generate a constraint that has the same fields as T:

    function interpolateParams(
        route: string, 
        params: T) : string { /*...*/ }
    

    Beware that trickery with circular type parameter constraints can sometimes cause problems, though this scenario will likely be OK.

提交回复
热议问题