Is there a way to create nominal types in TypeScript that extend primitive types?

前端 未结 5 637
悲&欢浪女
悲&欢浪女 2020-12-01 14:39

Say I have two types of numbers that I\'m tracking like latitude and longitude. I would like to represent these variables with the basic num

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 14:50

    Based on Lodewijk Bogaards answer

    interface Casted extends Number {
      DO_NOT_IMPLEMENT
      toManipulate: { castToNumberType:numberType, thenTo: number } 
    }
    
    interface LatitudeNumber extends Casted {
      LatitudeNumber
    }
    
    interface LongitudeNumber extends Casted {
      LongitudeNumber
    }
    type numberType = number | Casted
    var lat = 5
    
    function doSomethingStupid(long: LongitudeNumber,lat: LatitudeNumber) {
      var x = long;
      x += 25;
      return { latitude:lat, longitude:x }
    }
    
    var a = doSomethingStupid(3.067, lat)
    
    doSomethingStupid(a.longitude,a.latitude)
    

    I think doing the direct cast keeps the intention of a nominal type clear, the numberType Type unfortunately is needed because of a strange design descision where casting to number or Number still won't allow additions. The transpiled javascript is very simple with no boxing:

    var lat = 5;
    
    function doSomethingStupid(long, lat) {
        var x = long;
        x += 25;
        return { latitude: lat, longitude: x };
    }
    var a = doSomethingStupid(3.067, lat);
    doSomethingStupid(a.longitude, a.latitude);
    

提交回复
热议问题