镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Typecast string to string literal #12879

Description

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

Activity

  1. stochris commented on Dec 13, 2016

    @stochris
    Author

    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');
    
  2. ahejlsberg commented on Dec 13, 2016

    @ahejlsberg
    Member

    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.

  3. stochris commented on Dec 13, 2016

    @stochris
    Author

    Thank you very much. Problem solved

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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