gpt4 book ai didi

javascript - 有条件地在基类上指定方法/ Prop

转载 作者:行者123 更新时间:2023-11-30 20:54:19 25 4
gpt4 key购买 nike

与其他 JS 开发人员一样,我对以 TypeScript 编译器可以理解的静态方式编写内容有些陌生。我的基本用例是自定义通用类上可用的操作以访问 REST 端点。我可以根据构造函数参数动态地将方法/ Prop 添加到基类,但是动态地(可以理解地)做一些事情会使智能感知不正确。我知道我只是在想这个错误,并且有不同的范例来实现我想要的。我如何以编译器理解的方式从子类自定义基类?

这是我正在尝试的:

class Endpoint<T> {
constructor(
methods: Array<'GET' | 'CREATE'>
) {
// Conditionally add methods to the endpoint based on what was passed in
if (methods.includes('GET')) {
this.get = function get(id: string): Promise<T> {
return new Promise<T>(resolve => resolve());
};
}
if (methods.includes('CREATE')) {
this.create = function create(body: T): Promise<T> {
return new Promise<T>(resolve => resolve());
};
}
}

public get?: (id: string) => Promise<T>;
public create?: (body: T) => Promise<T>;
}

class User extends Endpoint<IUser> {
constructor() {
super(['GET']);
}
}

let u = new User();
// u.create will get transpiled away, but still shows up in intellisense

最佳答案

您可以缩短这段代码,但它并不漂亮,但基本思想是使用 mixins在 Typescript 2.2 中引入:

class Endpoint<T> {
}

type Constructor<T> = new(...args: any[]) => T;

function Gettable<T, U extends Constructor<Endpoint<T>> = typeof Endpoint>(Base: U) {
return class extends Base {
get(id: string): Promise<T> {
return new Promise<T>(resolve => resolve());
}
}
}

function Createable<T, U extends Constructor<Endpoint<T>> = typeof Endpoint>(Base: U) {
return class extends Base {
create(body: T): Promise<T> {
return new Promise<T>(resolve => resolve());
}
}
}

class User extends Gettable<IUser>(Endpoint)<IUser> {
}

const u = new User();
u.get("id"); // ok
u.create(); // error, method doesn't exist

关于javascript - 有条件地在基类上指定方法/ Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com