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

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

Nodejs typescript: declarer custom data type

问题

只更改每个的数据类型:

  1. data: { x: 1 } as anotherTypeX
  2. data: { y: 1 } as anotherTypeY
英文:

I have multiple services and all of them return same result:

  1. type result = {
  2. success: boolean
  3. data?: any
  4. }
  5. const a = async (): Promise<result> => {
  6. ...
  7. }
  8. const b = async (): Promise<result> => {
  9. ...
  10. }

But data of a is different of b:

  1. const a = async (): Promise<result> => {
  2. return {
  3. success: true,
  4. data: { x: 1 }
  5. }
  6. }
  7. const b = async (): Promise<result> => {
  8. return {
  9. success: true,
  10. data: { y: 1 }
  11. }
  12. }

And I want to change only data type for each one

  1. data: { x: 1 } as anotherTypeX
  2. data: { x: 1 } as anotherTypeY

答案1

得分: 0

使用泛型将为您解决这个问题,并为您提供适当的类型支持。

查看文档这里

  1. type result<T> = {
  2. success: boolean;
  3. data?: T;
  4. }
  5. type A = {
  6. x: number;
  7. }
  8. type B = {
  9. y: number;
  10. }
  11. const a = async (): Promise<result<A>> => {
  12. return {
  13. success: true,
  14. data: { x: 1 }
  15. }
  16. }
  17. const b = async (): Promise<result<B>> => {
  18. return {
  19. success: true,
  20. data: { y: 1 }
  21. }
  22. }
英文:

The use of generics will solve this issue for you and you will have proper typing support.

See docs here

  1. type result&lt;T&gt; = {
  2. success: boolean;
  3. data?: T;
  4. }
  5. type A = {
  6. x: number;
  7. }
  8. type B = {
  9. y: number;
  10. }
  11. const a = async (): Promise&lt;result&lt;A&gt;&gt; =&gt; {
  12. return {
  13. success: true,
  14. data: { x: 1 }
  15. }
  16. }
  17. const b = async (): Promise&lt;result&lt;B&gt;&gt; =&gt; {
  18. return {
  19. success: true,
  20. data: { y: 1 }
  21. }
  22. }

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:

确定