Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I restrict an interface type based on a generic parameter?

Given:

interface Foo<T> {
  data: T[] | SomeWrapper<T>
}

I want to change this so that data can only be an array if T = string. So if this syntax worked, I’d do

interface Foo<T> {
  data: T === typeof(string) 
          ? T[] | SomeWrapper<T> 
          : SomeWrapper<T>
}

I feel like there’s some solution with never here, but not sure how to construct it…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use conditional types for this.

interface Foo<T> {
  data: T extends string ? SomeWrapper<T>[] : SomeWrapper<T>
}

The syntax is similar as for ternary expressions and lets you define types according to some logic around what a given type extends. So a basic and clear example would be

type IsString<T> = T extends string ? true : false

Given the above type, IsString<"hi"> has type true and IsString<5> has type false.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading