2

How can I express warningMessage is only allowed to hold a value of online or 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 Answer 1

1

You can use a union of string literal types:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.