网站搜索

Typescript:在接口中为一个键指定多个可能的值


我如何表达 warningMessage 只能包含 'online' 或 'offline' 的值?

      interface DataInterface {
        shared?: {
            bio?: string;
            country?: string;
            dob?: Date;
            email?: string;
            fullName?: string;
            gender?: string;
            username?: string;
            warningMessage?: string; // <== How can I express this can only hold a value of online or offline?
            webSite?: string;
        };
      }
      const data: DataInterface = {};
      if (true) data.shared.warningMessage = 'Online';
      if (true) data.shared.warningMessage = 'Offline';
      if (true) data.shared.warningMessage = "This should fail as its not 'Online' or 'Offline'";
    ```

答案#1

你可以使用字符串字面量类型的联合:

interface DataInterface {
  shared: {
    bio?: string;
    country?: string;
    dob?: Date;
    email?: string;
    fullName?: string;
    gender?: string;
    username?: string;
    warningMessage?: "Online" | "Offline"; // <== How can I express this can only hold a value of online or offline?
    webSite?: string;
  };
}
const data: DataInterface = {
  shared: {}
};
data.shared.warningMessage = 'Online';
data.shared.warningMessage = 'Offline';
//Err
data.shared.warningMessage = "This should fail as its not 'Online' or 'Offline'";

游乐场链接