Closed
Description
TypeScript Version: 2.1.5
Code
I frequently run into situations where I have a computed key from another key, both of which are string literals:
type Key = "a" | "b" | "c";
type CombinedKey = "z.a" | "z.b" | "z.c";
declare const key: Key;
const combined: CombinedKey = `z.${key}`; // Can only be valid values: "z.a" | "z.b" | "z.c"
// Error: Type 'string' is not assignable to type 'CombinedKey'.
Expected behavior:
Since z.${Key}
can only be valid literal values of CombinedKey
it would be helpful if it compiled without error.
Actual behavior:
Error Type 'string' is not assignable to type 'CombinedKey'
.
I can workaround using an assertion:
const combined: CombinedKey = `z.${key}` as CombinedKey;
But this allows Key
or CombinedKey
to become incompatible without a compile error:
type Key = "wrong";
type CombinedKey = "z.a" | "z.b" | "z.c";
declare const key: Key;
const combined: CombinedKey = `z.${key}` as CombinedKey; // No error for "z.wrong"