lonewarrior556
lonewarrior556

Reputation: 4519

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

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?

Upvotes: 2

Views: 121

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250376

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
}

Upvotes: 5

Related Questions