Home > Blockchain >  Get the type of a property of an Union Type in typescript
Get the type of a property of an Union Type in typescript

Time:03-04

Suppose we have some interfaces with a name property (and possibly others):

interface Circle {
   name: 'circle',
   radius: number
}

interface Sphere {
   name: 'sphere',
   radius: number
}

interface Square {
   name: 'square',
   side: number
}

type GeometricalObject = Circle | Sphere | Square;

Now, suppose we have a function:

   doSomething(name: SomeType) {
     ...     
   }

Is there a way to assure that the name argument's type of doSomething() function is the union of the name property possible types in GeometricalObject (i.e. 'circle' | 'sphere' | 'square', in this specific case) programmatically?

I was imagining something like typeof GeometricalObject.name, if that was possible.

CodePudding user response:

interface Circle {
   name: 'circle',
   radius: number
}

interface Sphere {
   name: 'sphere',
   radius: number
}

interface Square {
   name: 'square',
   side: number
}

type GeometricalObject = Circle | Sphere | Square;

type Name = GeometricalObject["name"]; // "circle" | "sphere" | "square"

It is possible; it's using bracket notation instead of dot notation.

Playground

CodePudding user response:

you can do something like this

interface Circle {
    name: 'circle',
    radius: number
}

interface Sphere {
    name: 'sphere',
    radius: number
}

interface Square {
    name: 'square',
    side: number
}

type GeometricalObject = Circle | Sphere | Square;

type GeometricalObjectType = Circle['name'] | Sphere['name'] | Square['name'];
function doSomething(name: GeometricalObjectType) {
    switch(name) {
        case 'circle':
        break;
        case 'sphere':
        break;
        case 'square':
        break;
    }
}

TS Playground: https://www.typescriptlang.org/play?ssl=29&ssc=1&pln=1&pc=1#code/AQ4SwOwFwUwJwGYEMDGNgGExxQG3QN4BQopwESAtjAFzADkK2eM9ANCWSHEgCZgBXAM50IAygCN4nEAF8iM8NHjI0wAMoAHABbxCi0hWp16QnXvYHQPfsNHipcRfMWRYiVOnUBHAUjj6XCBGtAxCvv6sHEHAQmC8oWKS0qQupFAAnproAOIwAPbUUHBgKEi4APISAFYwKFDAALyYzPjAAD4a5gEdGhEBANwK6Vm5BUUlZZU1dVAAKqNNLTj4ANr0IfQAur1augHrmzudPn4HG1SsW0OkCAIQ9WD5EMC8 eqFMFDakADmABQhOh5T7FUrlKq1eoLbIASmAxBiQgA7mAoChtIDLvDETFQGUhOhGK1WDQrFwJAEkABrG54kAEolmfak8lkSkwGl0 mMsL9Vn0kAcrls SpIhAA

  • Related