Skip to content

Typecast string to string literal #12879

Closed
@stochris

Description

@stochris

TypeScript Version: 2.1.4

Code

// in 2.1.4  iShouldBeStringLiteral is now a string
let iShouldBeStringLiteral = type('This is a string')
export function type<T>(label: T | ''): T {
  return <T>label;
}

Expected behavior:
Before updating to typescript 2.1.4 the function transformed string to string literals with the same value
Actual behavior:
Now, even though the function returns a string literal type, assigning the return value to a variable / object property, will downcast it to string
function_type
variable_type

In the second image, I would expect x to be of type 'String literal'

This is especially in redux like scenarions, where you have to switch based on a constant and need the exhaustive checking in order to get type safety inside every case branch

edit: I know the solution is a bit hackish, but it helps a lot. If there is any other way of doing this, I'm more than open to suggestions

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions