0

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

  • {}
  • null
  • never

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Might be useful, the PR introducing never: github.com/Microsoft/TypeScript/pull/8652. You can find there that: Because never is a subtype of every type, it is always omitted from union types and it is ignored in function return type inference as long as there are other types being returned.
So what would happen to a property in the ISomething<TMulti extends object = never> that would have a property manNotBe: TMulti. Does that mean taht when TMulti is never that the property doesn't exist?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.