我正在学习打字稿,目前,我正试图在一个现有的Vue3项目上实现它。
考虑到这种古老的混合方法:
export const promises = {
methods: {
async process(...args): Promise<unknown> {
return await Promise.all(args.map(async (arg) => {
return await this.getResult(arg);
}));
},
}
};当我从另一个组件调用process时,我得到了这个错误:
TS2349:这个表达式是不可调用的。其他类型的“从不”没有呼叫签名。
我不明白:为什么打字本指的是never类型?我怎么才能解决这个问题?
发布于 2022-04-07 05:27:00
TS中的Mixins只能推断出所给出的信息。不能推断未显式提供的信息(尤指)。与混合模式相关,在该模式中,它只在末尾被组合。因此,我们可以利用大量的TS特性来帮助我们实现混音模式。参见https://www.typescriptlang.org/docs/handbook/mixins.html上推荐的方法
我继续修改了this.methods.process或this.methods.getResult,仅仅是为了指导方法,因为使用这种模式更容易。
type Constructor = new (...args: any[]) => {};
type GConstructor<T = {}> = new (...args: any[]) => T;
class MyBase {
constructor() {}
async getResult(a: any) {return a}
}
type MyBaseable = GConstructor<MyBase>
function Promises<TBase extends MyBaseable>(Base: TBase) {
return class PromiseClass extends Base {
async process (...args: any[]): Promise<unknown> {
return await Promise.all(args.map(async (arg) => {
return await this.getResult(arg);
}));
}
};
}
const Mixer = Promises(MyBase);
(async () => {
const myInstance = new Mixer()
const _ = await myInstance.process('a', 'b', 'c')
})()或者,如果您想保留this.methods,您可以这样做:
class MyBase {
// Use private members
_baseMethods = {
getResult: async (a: any) => {return a}
}
constructor() {}
}
type MyBaseable = GConstructor<MyBase>
function Promises<TBase extends MyBaseable>(Base: TBase) {
return class PromiseClass extends Base {
// Merge in the most outer-mixin as members
methods = {
...this._baseMethods,
process: async (...args: any[]): Promise<unknown> => {
return await Promise.all(args.map(async (arg) => {
return await this._baseMethods.getResult(arg);
}));
}
}
};
}在TS游乐场上查看此
更多关于TS混音的阅读:
https://stackoverflow.com/questions/71747630
复制相似问题