打字稿:为接口中的键指定多个可能的值

时间:2019-12-12 17:02:26

标签: typescript

我如何表达warningMessage只允许保留在线或离线值?

      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 个答案:

答案 0 :(得分: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'";

Playground Link