Is it possible to extend a Type that could be Null?

Viewed 60

I have a type I would like to extend, however my only reference to it has it defined as

type Foo = TypeIamInterestedIn | null

This is with strictNullChecks on.

Here is a tsPlayground example:

type Test1 = { name: string }
type Test2 = { name: string } | null

interface ExtendedTest1 extends Test1 {
    date: number
}

interface ExtendedTest2 extends Test2 { // type error an interface may only extend a class or another interface
    date: number
}

Is there anyway to just select the non-null type to extend here?

1 Answers

You can use Exclude to get null out of there. Exclude is a conditional type that will remove the second type parameter from the first type parameter. In this case we can remove the null type from the union type.

type Test2 = { name: string } | null

interface ExtendedTest2 extends Exclude<Test2, null> { 
    date: number
}
Related