Typescript:Union函数参数Typescript
我想按颜色或系列搜索小部件(至少需要一个)。这不会编译:Typescript:Union函数参数Typescript,typescript,Typescript,我想按颜色或系列搜索小部件(至少需要一个)。这不会编译: 导出函数小部件(参数:{colorId:number}{seriesId:number}){ if(参数colorId){ //按颜色搜索小部件 }否则{ //按系列搜索小部件 } } 错误:属性“colorId”在类型“{colorId:number;}{seriesId:number;}”上不存在。 我知道我可以这样做: type ColorId={ColorId:number}; 函数isColorId(params:any):p
导出函数小部件(参数:{colorId:number}{seriesId:number}){
if(参数colorId){
//按颜色搜索小部件
}否则{
//按系列搜索小部件
}
}
错误:属性“colorId”在类型“{colorId:number;}{seriesId:number;}”上不存在。
我知道我可以这样做:
type ColorId={ColorId:number};
函数isColorId(params:any):params是ColorId{
返回类型params.colorId==“number”;
}
导出函数小部件(参数:{colorId:number}{seriesId:number}){
if(isColorId(params)){
//按颜色搜索小部件
}否则{
//按系列搜索小部件
}
}
我所寻找的是一个具有较少样板文件的解决方案。似乎应该有更优雅的方式来实现这一点。在这种情况下,缩小类型的最短方法是在类型保护中使用
:
export function widgets(params: {colorId: number} | {seriesId: number}) {
if ('colorId' in params) {
params.colorId
// Search widgets by color
} else {
params.seriesId
// Search widgets by series
}
}
在这种情况下,缩小类型的最短方法是在
类型保护中使用:
export function widgets(params: {colorId: number} | {seriesId: number}) {
if ('colorId' in params) {
params.colorId
// Search widgets by color
} else {
params.seriesId
// Search widgets by series
}
}
完美!我知道一定会有这样的事。太好了!我知道一定会有这样的事。