Typescript: object with at least one property of type T

前端 未结 2 1244
陌清茗
陌清茗 2020-12-11 21:13

How can I write HasNumber without typescript giving me an error because on HasNumberAndString name is not a number? I want a way to en

相关标签:
2条回答
  • 2020-12-11 21:31

    There is no great way in TypeScript to allow a type with an index signature to have an additional property that doesn't match the index signature type. See microsoft/TypeScript#17867 for the suggestion to allow exceptions to index signatures, and maybe give it a

    0 讨论(0)
  • 2020-12-11 21:31

    You could use union types to allow any property of type string or number:

    interface HasNumber {
        [key: string]: number;
    }
    
    interface HasNumberAndString {
        [key: string]: string | number;
    }
    

    But this will not enforce having at least one property of each type.

    0 讨论(0)
提交回复
热议问题