我如何表达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'";
```
答案 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'";