Robert Koritnik
Robert Koritnik

Reputation: 105009

Typescript generic type default when not being used

I have an interface similar to this:

interface ISomething<TMulti extends object> {
    value: number | string;
    text: string | TMulti;
}

The text part could either be a simple string or an object map implementing some specific interface. In majority of cases it's going to be just a simple non-nullable string, so I would like to set the TMulti generic type default to something to east the use of this interface. My choices are

The best option seems to be never but I've never seen it used as a generic type default and am not exactly sure what a type of string | never actually means? Is it identical to string? Both of the other two options, allow me to set the value of text to some undesired value.

The question is: can type never be used as a generic type default and what does it mean is such case?

Additional note: I'm using Typescript in strict mode, so string can't be null per compiler requirements, which is also what I want.

Upvotes: 0

Views: 1552

Answers (1)

Fenton
Fenton

Reputation: 250822

Yes, you can use never as a default:

interface ISomething<TMulti extends object = never> {
    value: number | string;
    text: string | TMulti;
}

const a: ISomething = {
    value: 'str',
    text: 'str'
}

const b: ISomething<{ example: string }> = {
    value: 2,
    text: {
        example: 'str'
    }
}

The examples above show that where you don't specify the type, it knows text should be a string. So never is a good choice, for which you should be congratulated as I feel fraudulent simply confirming your correct suggestion.

Upvotes: 1

Related Questions