【问题标题】:TypeScript: for(const a of ["a", "b"]) typeof a = "a" | "b"打字稿: for(const a of ["a", "b"]) typeof a = "a" | “乙”
【发布时间】:2022-01-27 09:06:39
【问题描述】:

如果我们编写简单的构造,我们有:

for(const a of ["a", "b"]) {
    type b = typeof a; // string
}

有没有办法?

for(const a of ["a", "b"]) {
    type b = typeof a; // "a" | "b"
}

不重复所有字符串两次?

for(const a of ["a", "b"] as (("a" | "b")[])) {
    type b = typeof a; // "a" | "b"
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    声明数组as const,这样它就不会扩大到string[]

    for(const a of ["a", "b"] as const) {
        type b = typeof a; // "a" | "b"
    }
    

    【讨论】:

    • in/of 只是一个错字,谢谢as const
    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2021-11-28
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 2021-10-06
    相关资源
    最近更新 更多