Skip to content

String literal type from string template #14584

Closed
@aaronbeall

Description

@aaronbeall

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"

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions