是否可以扩展可能为 Null 的类型?

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

我想扩展一个类型,但是我对它的唯一引用将其定义为

type Foo = TypeIamInterestedIn | null

这是 strictNullChecks 开启的。

这是一个 tsPlayground 示例:

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
}

这里是否只有 select 非空类型可以扩展?

您可以使用 Exclude 从那里得到 nullExclude 是一种条件类型,它将从第一个类型参数中删除第二个类型参数。在这种情况下,我们可以从联合类型中删除 null 类型。

type Test2 = { name: string } | null

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