Typescript 以类型安全的方式检查对象中可能的属性
TypeScript 2.0支持如下标记的联合:Typescript 以类型安全的方式检查对象中可能的属性,typescript,typescript2.0,Typescript,Typescript2.0,TypeScript 2.0支持如下标记的联合: type Foo = { tag: 'foo' x: number } type Bar = { tag: 'bar' y: string } type FooOrBar = Foo | Bar function doStuff2(foobar: Foo2OrBar2) { if ((<Foo2>foobar).x != undefined){ console.log((<
type Foo = {
tag: 'foo'
x: number
}
type Bar = {
tag: 'bar'
y: string
}
type FooOrBar = Foo | Bar
function doStuff2(foobar: Foo2OrBar2) {
if ((<Foo2>foobar).x != undefined){
console.log((<Foo2>foobar).x + 5)
} else {
console.log((<Bar2>foobar).y.length)
}
}
然后我们可以通过类型安全的方式区分这些情况:
function doStuff(foobar: FooOrBar) {
if (foobar.tag === 'foo') {
console.log(foobar.x + 3)
} else {
console.log(foobar.y.length)
}
}
一切都很好。但实际上,标记
字段并不是区分这些类型所必需的。我们可以设想这样做:
type Foo2 = {
x: number
}
type Bar2 = {
y: string
}
type Foo2OrBar2 = Foo2 | Bar2
有没有类似的方法可以用类型安全的方式对这样的联合进行案例分析?显而易见的事情是行不通的:
function doStuff2(foobar: Foo2OrBar2) {
if ('x' in foobar) {
// Type error: Property 'x' does not exist on type 'Bar2'
console.log(foobar.x + 5)
} else {
// Type error: Property 'y' does not exist on type 'Foo2'
console.log(foobar.y.length)
}
}
还有别的方法吗?我想出了一个通用的方法: 更新 在中,有一个TypeScript票证,可以让
扮演一个类型守卫:
我想出了一个通用的方法:
更新
在
中,有一个TypeScript票证,可以让扮演一个类型守卫:
您可以尝试以下方法:
type Foo = {
tag: 'foo'
x: number
}
type Bar = {
tag: 'bar'
y: string
}
type FooOrBar = Foo | Bar
function doStuff2(foobar: Foo2OrBar2) {
if ((<Foo2>foobar).x != undefined){
console.log((<Foo2>foobar).x + 5)
} else {
console.log((<Bar2>foobar).y.length)
}
}
函数doStuff2(foobar:Foo2OrBar2){
如果((foobar).x!=未定义){
console.log((foobar.x+5)
}否则{
console.log((foobar.y.length)
}
}
您可以尝试以下方法:
type Foo = {
tag: 'foo'
x: number
}
type Bar = {
tag: 'bar'
y: string
}
type FooOrBar = Foo | Bar
function doStuff2(foobar: Foo2OrBar2) {
if ((<Foo2>foobar).x != undefined){
console.log((<Foo2>foobar).x + 5)
} else {
console.log((<Bar2>foobar).y.length)
}
}
函数doStuff2(foobar:Foo2OrBar2){
如果((foobar).x!=未定义){
console.log((foobar.x+5)
}否则{
console.log((foobar.y.length)
}
}
这是不安全的。TypeScript官方文档中有类似的内容:在更多的typesafe通用选项出现之前编写的。这是不安全的。TypeScript官方文档中也有类似的内容:在更多的typesafe通用选项出现之前编写的。