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

Typecast string to string literal #12879

Closed
stochris opened this issue Dec 13, 2016 · 3 comments
Closed

Typecast string to string literal #12879

stochris opened this issue Dec 13, 2016 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@stochris
Copy link

stochris commented Dec 13, 2016

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

@stochris
Copy link
Author

stochris commented Dec 13, 2016

Also, the non templated version the function works as intended

function type(val: any){
    return <'this is string literal'>val;
}

// stringLiteral appears as ' let stringLiteral: "this is string literal" '
let stringLiteral = type('this is string literal');

@ahejlsberg
Copy link
Member

ahejlsberg commented Dec 13, 2016

In 2.1 we preserve literal types of expressions and variables for a long as possible, but when we infer a literal type for a mutable location such as a let or var variable, we widen to the base primitive type. However, if you declare iShouldBeStringLiteral using const you shouldn't need the type function at all.

For more details see #10676.

@stochris
Copy link
Author

Thank you very much. Problem solved

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Dec 13, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants