【问题标题】:How can I validate if the content of a string is accepted using interfaces of TS?如何使用 TS 的接口验证字符串的内容是否被接受?
【发布时间】:2023-04-10 19:27:02
【问题描述】:

我想检查一个字符串的内容是否被接受。

export interface paramsHttpRequest {
    type: string, // This type should be "POST" or "GET"
    url: string,
    headers?: [object],
    body?: JSON
}

如何确保该类型以 POSTGET 的形式出现?

【问题讨论】:

  • 大概你想要一个字符串文字类型的联合,比如this,所以"POST" | "GET"而不是string。这能满足你的需求吗?如果没有,请edit代码示例演示不满意的用例。
  • 是的@jcalz,这正是我需要的。谢谢!

标签: typescript interface


【解决方案1】:

TypeScript 有字符串literal types,它们在类型系统中表示为带引号的字符串文字。字符串文字类型仅接受单个特定的字符串值。例如,"POST" 类型只接受值"POST"

let a: "POST";
a = "POST"; // okay
a = "GET"; // error! Type '"GET"' is not assignable to type '"POST"'

TypeScript 还有union types,用竖线连接其他类型来表示(|);所以如果AB 是类型,那么A | B 是一个联合类型,AB 作为联合的成员。当且仅当该值被至少一个成员接受时,联合类型才接受该值:

let b: string | number;
b = "hello"; // okay
b = 123; // okay
b = false; // error! Type 'boolean' is not assignable to type 'string | number'

如果您希望ParamsHttpRequesttype 属性只接受"POST""GET" 而没有其他内容,那么您应该将其声明为"POST" | "GET" 类型:

interface ParamsHttpRequest {
    type: "POST" | "GET"
    url: string,
    headers?: [object],
    body?: JSON
}

const x: ParamsHttpRequest = {
    type: "GET",
    url: "/"
} // okay

const y: ParamsHttpRequest = {
    type: "OOPS", // error!
    // Type '"OOPS"' is not assignable to type '"POST" | "GET"'
    url: "/"
}

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2014-08-25
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多