I have two values from a select option. For better readability, I defined the only two possible values that the user can choose, but I'm getting a type error with this approach:
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 { }
Am I doing it the wrong way or this is not possible?
CodePudding user response:
Perhaps, you can create a type which is valueof SERVERS.
const SERVERS = {
SERVER_A: 'A',
SERVER_B: 'B',
} as const;
type SERVERS_VALUE = typeof SERVERS[keyof typeof SERVERS];
And declare server with SERVERS_VALUE type.
server: SERVERS_VALUE;
This method can be amended to
setServer(server: SERVERS_VALUE) { }
Instead of:
setServer(server: 'A' | 'B') { }
