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…
>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.