[英]conditonal function typing in a object {typescript}
how do i do conditonal function typing in an object?我如何在 object 中输入条件 function?
let obj = {
function myfunc (input: string): number;
function myfunc (input: number): string;
myfunc: function (input: string|number):string|number {
...
}
}
does not work, it gives me syntax errors and i've tried multiple methods too but they all gave syntax errors不起作用,它给了我语法错误,我也尝试了多种方法,但它们都给出了语法错误
some examples of my attempt:我尝试的一些例子:
let obj = {
myfunc (input: string): number;
myfunc (input: number): string;
myfunc: function (input: string|number):string|number {
...
}
}
let obj = {
function myfunc (input: string): number;
function myfunc (input: number): string;
myfunc: function (input: string|number):string|number {
...
}
}
let obj:{
function myfunc (input: string) : number;
function myfunc (input: number) : string;
myfunc: (input: string|number) => number|string
} = {
myfunc: function (input: string|number):string|number {
return ""
}
}
The following would do the trick.以下将做的伎俩。 The problem was declaring the type definition inside the object.问题是在 object 中声明类型定义。 Just split it out as a new interface type and you're good to go.只需将其拆分为新的接口类型,您就可以使用 go。
interface MyObj {
myfunc (input: string): number;
myfunc (input: number): string;
}
let obj: MyObj = {
myfunc: (input: any): any => {
return 1;
}
}
someone in the typescript discord gave me a solution that works very well: typescript discord 中的某个人给了我一个非常有效的解决方案:
let obj = {
myfunc: (() => {
function myfunc (input: string):number;
function myfunc (input: number):string;
function myfunc (input: string|number): number|string {
let a = input // string|number
return a
}
return myfunc
})()
}
obj.myfunc(0) // string
obj.myfunc("hello") // number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.