例如,我希望以下函数返回一个可以接受任何字符串或任何数字的函数,这取决于调用初始函数的方式,但它仅接受等于a
的字符串或数字:
function foo<A extends string | number>(a: A) : (b: A) => boolean {
return (b) => a === b;
}
foo("test") // creates a function that only accepts "test", want one that accepts any string.
foo(3) // creates a function that only accepts 3, want one that accepts any number.
如何键入此函数,使其按需工作?
答案 0 :(得分:2)
如果您只删除extends string
,它似乎可以满足您的要求
function foo<A>(a: A) : (b: A) => boolean {
return (b) => a === b;
}
如果您想限制输入类型并且仍然让它们通过,则可以执行以下操作
function foo(a:string): (b:string) => boolean
function foo(a:number): (b:number) => boolean
function foo(a:boolean): (b:boolean) => boolean
function foo (a: string|number|boolean) : (b: string|number|boolean) => boolean {
return (b) => a === b;
}
foo("test")("a") //expects string
foo(1)(2) //expects number
答案 1 :(得分:-1)
似乎这样做的方法是使用重载:
function foo(a1: number): (a2: number) => boolean;
function foo(a1: string): (a1: string) => boolean;
function foo(a1: number | string): (a2: number|string) => boolean {
return (a2) => a1 === a2;
}