我有一种情况,我有一个类型,它是两个函数的联合,它们的文字值作为其参数之一的类型.归结为一个最小的例子,它基本上是这样的:
type FetchMini = (id: number, representation: 'mini') => MiniUser;
type FetchFull = (id: number, representation: 'full') => FullUser;
function f(fetchUser: FetchMini | FetchFull) {
fetchUser(2, 'mini');
fetchUser(2, 'full');
}
Run Code Online (Sandbox Code Playgroud)
这两个调用都使编译器失败并显示以下消息:
无法调用类型缺少调用签名的表达式.输入'FetchMini | FetchFull'没有兼容的呼叫签名
我想我明白了这种情况发生的原因,(......我想),但我该怎么办呢?
这是一个类似的问题,但它没有答案:即使参数满足每个函数的约束,函数联合也不可调用
小智 11
您的fetchUser()基本上是一个重载函数,它接受两个 mini和full,从而应相交 -typed,而不是结合.
type MiniUser = { name: string }
type FullUser = { firstName: string, lastName: string, age: number }
type FetchMini = (id: number, representation: 'mini') => MiniUser;
type FetchFull = (id: number, representation: 'full') => FullUser;
type FetchBoth = FetchMini&FetchFull
function f(fetchUser: FetchBoth) {
fetchUser(2, 'mini');
fetchUser(2, 'full');
}
function fetchBoth(id: number, representation: 'mini'): MiniUser
function fetchBoth(id: number, representation: 'full'): FullUser
function fetchBoth(id: number, representation: 'mini' | 'full') {
if (representation==='mini')
return { name: 'Mini' }
if (representation==='full')
return { firstName: 'Full', lastName: 'User', age: 20 }
}
f(fetchBoth)
Run Code Online (Sandbox Code Playgroud)
作为一个经验法则,当你宣布接受参数数量的函数都 A型和 B,该功能应该与 -typed.
嗯,看起来最初的想法有点不正确。您应该决定您想要实现什么行为。
据我所知,f接受一个负责获取用户的函数。根据提供的函数,将返回MiniUser或FullUser 。如果我的建议是正确的,请考虑以下示例:
class MiniUser {
name: string;
constructor(name: string) {
this.name = name;
}
}
class FullUser extends MiniUser {
age: number;
constructor(name: string, age: number) {
super(name);
this.age = age;
}
}
function fetchMiniFn(id: number) {
return new MiniUser("John");
}
function fetchFullFn(id: number) {
return new FullUser("John", 22);
}
function f(fetchUser: (id: number) => MiniUser | FullUser) {
let a = fetchUser(2);
if (a instanceof FullUser) {
console.log("Full User: " + a.name + ", " + a.age);
}
else {
console.log("Mini User: " + a.name);
}
}
// Call the function to fetch MiniUser
f(fetchMiniFn);
// Call the function to fetch FullUser
f(fetchFullFn);
Run Code Online (Sandbox Code Playgroud)
如果我最初的建议不正确,并且您仍然希望函数f决定必须获取哪种类型的 User,那么您可以将上面的代码转换为:
function fetch(id: number, representation: 'mini' | 'full') {
if (representation == 'mini') {
return new MiniUser("John");
}
else {
return new FullUser("John", 22);
}
}
type FetchUser = (id: number, representation: 'mini' | 'full') => MiniUser | FullUser;
function f(fetchUser: FetchUser) {
// Call the function with MiniUser fetching
let mini = <MiniUser>fetchUser(2, 'mini');
console.log("Mini User: " + mini.name);
// Call the function with FullUser fetching
let full = <FullUser>fetchUser(2, 'full');
console.log("Full User: " + full.name + ", " + full.age);
}
// Call function:
f(fetch);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2979 次 |
| 最近记录: |