ts写法请教,大佬在线否?

作者站长头像
站长
· 阅读数 10

ts写法请教,大佬在线否?

ts写法请教,大佬在线否?这种时候怎么办?需要分开写两个方法吗?

function test1(a: Type1 | Type2) {
}

function test2(a: Type1) {
}

方法 2 不能理解赋值给方法 1 吗?

追加 1

export interface ResCategoryLabel {
    categoryType: "genre" | "level";
    categoryId: number;
    categoryName: string;
}

export interface Major {
    id: number;
    name: string;
}

追加 2

在这个通用的组件里面定义俩个方法区分是可以ts写法请教,大佬在线否?或者直接类型改成 anyts写法请教,大佬在线否?

虽然不报错了,但是这样作法合适吗?有其他好的解决方法吗?

回复
1个回答
avatar
test
2024-07-05

你的代码等效于以下代码

function test(index:number,label:Major | ResCategoryLabel){
    console.log(label)
}
function test2(index:number,label:Major){
     console.log(label)
}
const a:Major = {
    id:1,
    name:'pb'
}
//这里相当于你的onchange,它只接受 如下定义的callback
function fun1(callback:(index:number,label:Major | ResCategoryLabel)=>void){
    return callback(1,a)
}


fun1(test) // test(index:number,label:Major | ResCategoryLabel),参数类型完全一致,所以不报错 
fun1(test2)//出错 test2(index:number,label:Major) 参数类型不同,报错
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容