如何使用TypeScript接口校验字符串字段的取值是否符合要求
解决方案
你可以通过TypeScript的字符串字面量联合类型直接限制type字段的取值范围,修改后的接口定义如下:
export interface paramsHttpRequest { type: "POST" | "GET", // 取值只能是POST或者GET url: string, headers?: [object], body?: JSON }
如果该请求方法的取值需要在多个场景复用,也可以单独抽离定义,以下是两种常用的扩展写法:
方案1:抽为独立类型别名
// 单独定义通用请求方法类型 type HttpMethod = "POST" | "GET" export interface paramsHttpRequest { type: HttpMethod, url: string, headers?: [object], body?: JSON }
方案2:使用枚举(适合取值后续需要扩展的场景)
enum HttpMethod { POST = "POST", GET = "GET" } export interface paramsHttpRequest { type: HttpMethod, url: string, headers?: [object], body?: JSON }
以上写法都可以在静态编译阶段完成type字段的取值校验,只要赋值不是预设的POST/GET,TypeScript会直接抛出类型错误。
内容的提问来源于stack exchange,提问作者Gabriel Fernandes
相关产品推荐
相关产品推荐

