我有兩個來自選擇選項的值。為了更好的可讀性,我定義了用戶可以選擇的僅有的兩個可能的值,但是使用這種方法會出現型別錯誤:
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 { }
我做錯了還是不可能的?
uj5u.com熱心網友回復:
也許,您可以創建type一個valueof SERVERS。
const SERVERS = {
SERVER_A: 'A',
SERVER_B: 'B',
} as const;
type SERVERS_VALUE = typeof SERVERS[keyof typeof SERVERS];
并server用SERVERS_VALUE型別宣告。
server: SERVERS_VALUE;
這個方法可以修改為
setServer(server: SERVERS_VALUE) { }
代替:
setServer(server: 'A' | 'B') { }
StackBlitz 上的示例演示
參考
物件與列舉
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421749.html
標籤:
