我有一个想要扩展的类型,但是我对它的唯一引用将其定义为
类型 Foo = TypeIamInterestedIn |空
这是启用了 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
}
有没有办法只选择非空类型来扩展这里?
最佳答案
您可以使用排除
从那里获取null
。 Exclude
是一个条件类型,它将从第一个类型参数中删除第二个类型参数。在这种情况下,我们可以从联合类型中删除 null
类型。
type Test2 = { name: string } | null
interface ExtendedTest2 extends Exclude<Test2, null> {
date: number
}
关于typescript - 是否可以扩展可能为 Null 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52330842/