[英]Create a generic post/put/get in typescript react
So I'm trying to learn writing more generic.所以我正在努力学习写作更通用。 I have POST/PUT/DELETE/GET for attatchments together with these entity types (there are also alot more entity types that I will need to add in the future).
我有用于附件的 POST/PUT/DELETE/GET 以及这些实体类型(将来我还需要添加更多的实体类型)。
This code works, and it is indeed more generic than writing 4 different getAttatchment with hardcorded personnel/workoder etc where it is ${apiType} currently.这段代码有效,而且它确实比使用硬编码人员/workoder 等编写 4 个不同的 getAttatchment 更通用,目前它是 ${apiType}。 Some progress made atleast.
至少取得了一些进展。
But how could I rewrite this even better?但是我怎样才能更好地重写它呢? I would like to have eg
getAttatchments<T>(EntityType<T> .....)
but I don't know how I could write it like that.我想要例如
getAttatchments<T>(EntityType<T> .....)
但我不知道我怎么能这样写。 And ofcourse it need to be typesafe so you don't actually pass entities that does not exist.当然,它需要是类型安全的,因此您实际上不会传递不存在的实体。
export enum EntityType {
Personnel = 'personnel',
Workorder = 'workorder',
Asset = 'asset',
AssetBooking = 'assetbooking',
}
async getAttachments(id: string | number, apiType: EntityType) {
return await this.get<AttachmentDetails[]>(
`attachment/${apiType}/${id}/attachment`
)
}
What you have already looks fairly generic but I would forgo the enum and use a union type instead.你已经看起来相当通用,但我会放弃枚举并使用联合类型。 eg
例如
type EntityType = 'personnel'|'workorder'|'asset'|'assetbooking'
type AttachmentDetails= any // whatever
// mock implementation
function get<T>( url:string) {
return ''
}
function getAttachments<T extends EntityType>(id: string | number, apiType: T) {
return get<AttachmentDetails[]>( `attachment/${apiType}/${id}/attachment` )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.