英文:
Nodejs typescript: declarer custom data type
问题
只更改每个的数据类型:
data: { x: 1 } as anotherTypeX
data: { y: 1 } as anotherTypeY
英文:
I have multiple services and all of them return same result:
type result = {
success: boolean
data?: any
}
const a = async (): Promise<result> => {
...
}
const b = async (): Promise<result> => {
...
}
But data of a
is different of b
:
const a = async (): Promise<result> => {
return {
success: true,
data: { x: 1 }
}
}
const b = async (): Promise<result> => {
return {
success: true,
data: { y: 1 }
}
}
And I want to change only data type for each one
data: { x: 1 } as anotherTypeX
data: { x: 1 } as anotherTypeY
答案1
得分: 0
使用泛型将为您解决这个问题,并为您提供适当的类型支持。
查看文档这里
type result<T> = {
success: boolean;
data?: T;
}
type A = {
x: number;
}
type B = {
y: number;
}
const a = async (): Promise<result<A>> => {
return {
success: true,
data: { x: 1 }
}
}
const b = async (): Promise<result<B>> => {
return {
success: true,
data: { y: 1 }
}
}
英文:
The use of generics will solve this issue for you and you will have proper typing support.
See docs here
type result<T> = {
success: boolean;
data?: T;
}
type A = {
x: number;
}
type B = {
y: number;
}
const a = async (): Promise<result<A>> => {
return {
success: true,
data: { x: 1 }
}
}
const b = async (): Promise<result<B>> => {
return {
success: true,
data: { y: 1 }
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论