【问题标题】:Argument of type 'string' is not assignable to parameter of type '"A" | "B"' when trying to assign possible values to a string“字符串”类型的参数不能分配给“A”类型的参数 |尝试将可能的值分配给字符串时的“B”'
【发布时间】: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


【解决方案1】:

也许,您可以创建一个type,它是valueof SERVERS

const SERVERS = {
  SERVER_A: 'A',
  SERVER_B: 'B',
} as const;

type SERVERS_VALUE = typeof SERVERS[keyof typeof SERVERS];

并用SERVERS_VALUE 类型声明server

server: SERVERS_VALUE;

这个方法可以修改为

setServer(server: SERVERS_VALUE) { }

代替:

setServer(server: 'A' | 'B') { }

Sample Demo on StackBlitz


参考

Objects vs Enums

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2021-10-13
    • 2018-06-24
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多