If we write the simple construct, we have:
for(const a of ["a", "b"]) {
type b = typeof a; // string
}
Is there a way to have?
for(const a of ["a", "b"]) {
type b = typeof a; // "a" | "b"
}
without repeating all the strings twice?
for(const a of ["a", "b"] as (("a" | "b")[])) {
type b = typeof a; // "a" | "b"
}
CodePudding user response:
Declare the array as const
so it doesn't get widened to string[]
.
for(const a of ["a", "b"] as const) {
type b = typeof a; // "a" | "b"
}