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

前端 未结 5 636
悲&欢浪女
悲&欢浪女 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 15:02

    You can approximate opaque / nominal types in Typescript using a helper type. See this answer for more details:

    // Helper for generating Opaque types.
    type Opaque = T & { __opaque__: K };
    
    // 2 opaque types created with the helper
    type Int = Opaque;
    type ID = Opaque;
    
    // works
    const x: Int = 1 as Int;
    const y: ID = 5 as ID;
    const z = x + y;
    
    // doesn't work
    const a: Int = 1;
    const b: Int = x;
    
    // also works so beware
    const f: Int = 1.15 as Int;
    

    Here's a more detailed answer: https://stackoverflow.com/a/50521248/20489

    Also a good article on different ways to to do this: https://michalzalecki.com/nominal-typing-in-typescript/

提交回复
热议问题