【发布时间】:2022-01-27 11:13:09
【问题描述】:
我有两个来自选择选项的值。为了更好的可读性,我定义了用户可以选择的仅有的两个可能值,但是使用这种方法会出现类型错误:
HTML:
<div>
SERVER
<mat-select (selectionChange)="onChange($event)">
<mat-option value="A">Server A</mat-option>
<mat-option value="B">Server B</mat-option>
</mat-select>
</div>
TS:
const SERVERS = {
SERVER_A: "A",
SERVER_B: "B",
}
private origin: typeof SERVERS.SERVER_A | typeof SERVERS.SERVER_B = SERVERS.SERVER_A;
onChange(e) {
this.server = e.value;
this.setServer(this.server); // Argument of type 'string' is not assignable to parameter of type '"A" | "B"'.
}
setServer(server: "A" | "B"): void { }
是我做错了还是这不可能?
【问题讨论】:
-
你可能想要
const Servers = { /*...*/ } as const; -
你能展示
setServer方法吗? -
定义为 setServer(server: "A" | "B"): void { }
标签: html angular typescript types event-handling