对象分解结构中的Typescript条件类型
我想调用一个只有对象作为参数的函数。此对象可以是两个发生冲突的不同接口(1+属性具有相同的键,但可能的值不同) 在我的主函数中,如果对象中的类型值为iffoo,我想调用对象分解结构中的Typescript条件类型,typescript,Typescript,我想调用一个只有对象作为参数的函数。此对象可以是两个发生冲突的不同接口(1+属性具有相同的键,但可能的值不同) 在我的主函数中,如果对象中的类型值为iffoo,我想调用getFoo;如果对象中的类型值为ifbar,我想调用getBar interface Foo { title: string number: 1 | 2 } interface FooWithType extends Foo { type: 'foo' } interface Bar { title: stri
getFoo
;如果对象中的类型值为ifbar,我想调用getBar
interface Foo {
title: string
number: 1 | 2
}
interface FooWithType extends Foo {
type: 'foo'
}
interface Bar {
title: string
number: 3 | 4
}
interface BarWithType extends Bar {
type: 'bar'
}
function getFoo(params: Foo): void
function getBar(params: Bar): void
function main({ type, ...rest }: FooWithType | BarWithType) {
return type === 'foo' ? getFoo(rest) : getBar(rest)
}
当我在一个分解结构的对象上执行条件类型时,我遇到了一个类型脚本问题,其中类型“{title:string;number:3 | 4;}”不能分配给类型“Foo”
,因为我的rest
值在我进行类型检查时仍然是一个联合类型:
var rest: {
title: string;
number: 1 | 2;
} | {
title: string;
number: 3 | 4;
}
Typescript不理解rest类型,因为它的结构与类型值不相关。有两种可能的方法可以修复它,而无需编辑除主功能以外的任何内容
interface Foo {
title: string
number: 1 | 2
}
interface FooWithType extends Foo {
type: 'foo'
}
interface Bar {
title: string
number: 3 | 4
}
interface BarWithType extends Bar {
type: 'bar'
}
function getFoo(params: Foo): void
function getBar(params: Bar): void
function main({ type, ...rest }: FooWithType | BarWithType) {
return type === 'foo' ? getFoo(rest) : getBar(rest)
}
第一种是类型断言(不推荐使用):
第二种方法是不要破坏对象的结构(更好的方法):
function main(params: FooWithType | BarWithType) {
return params.type === 'foo' ? getFoo(params) : getBar(params)
}