Node.js TypeScript: 声明自定义数据类型

huangapple go评论58阅读模式
英文:

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&lt;T&gt; = {
  success: boolean;
  data?: T;
}

type A = {
   x: number;
}
type B = {
   y: number;
}

const a = async (): Promise&lt;result&lt;A&gt;&gt; =&gt; {
  return {
    success: true,
    data: { x: 1 }
  }
}

const b = async (): Promise&lt;result&lt;B&gt;&gt; =&gt; {
  return {
    success: true,
    data: { y: 1 }
  }
}

huangapple
  • 本文由 发表于 2023年4月4日 16:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定