如何在TypeScript中使用类属性数据类型声明一个常量数据类型?

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

How to declare a constant datatype using a class property datatype in typescript?

问题

我正在创建一个nestjs API,所以我正在使用类来声明我的实体,例如

export class Customer {
  id: number;
  name: string;
}

现在我正在编写我的Customer Controller,我想将一个查询参数的类型设置为customer.id,因为我在考虑如果有一天顾客的id数据类型自动更改为字符串,那么我的控制器查询参数也将变为字符串。

@GET()
getCustomerById(@Params('id') id: Customer['id']) {
  return this.customerService.getCustomerById(id);
}

是否可能?谢谢。

英文:

I'm creating a nestjs API so I'm using classes to declare my entities for example

export class Customer {
id: number;
name: string;
}

So now I'm working in my Customer Controller and I would like to type an get query param as customer.id because I'm thinking if some day the customer id data type changes to string automatically making my controller query param as string too.

@GET()
getCustomerById(@Params('id', id: Customer.id)) {
return this.customerService.getCustomerById(id))
}

Is it possible? Thanks

答案1

得分: 1

你可以使用 TypeScript 查找类型:

getCustomerById(@Params('id') id: Customer['id']) {}
英文:

You can use TypeScript lookup types:

getCustomerById(@Params('id') id: Customer['id']) {}

huangapple
  • 本文由 发表于 2023年6月1日 19:13:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381292.html
匿名

发表评论

匿名网友

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

确定