How to create 2 incompatible number-like types in TypeScript?

后端 未结 2 608
你的背包
你的背包 2021-01-04 11:12

I\'ve been trying to figure out how to create 2 mutually-incompatible number-like/integer types in TS.

For example, in the code below, height and weight are both num

2条回答
  •  梦毁少年i
    2021-01-04 12:03

    So, after banging my head against the wall for several hours, I managed to come up with this:

    class height extends Number {}
    class weight extends Number {}
    

    By sub-classing the Number class, Typescript allows you to create distinct numeric types.

    And then you can go and use the variables as specified above.

    var a: height = 68;
    var b: weight = 184;
    console.log(a+b); // Should be an error.
    

    The issue that I run into is that this also returns an error:

    console.log(a+a); // Should NOT be an error.
    

提交回复
热议问题