Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String literal type from string template #14584

Closed
aaronbeall opened this issue Mar 10, 2017 · 2 comments
Closed

String literal type from string template #14584

aaronbeall opened this issue Mar 10, 2017 · 2 comments
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@aaronbeall
Copy link

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"
@DanielRosenwasser
Copy link
Member

Related is #13969.

@RyanCavanaugh RyanCavanaugh added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Mar 13, 2017
@RyanCavanaugh
Copy link
Member

This hasn't collected much feedback and would open the door for a lot of combinatorially-explosive things we'd rather avoid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants