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 does not work #20271

Closed
sevenryze opened this issue Nov 26, 2017 · 2 comments
Closed

String Literal Type does not work #20271

sevenryze opened this issue Nov 26, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@sevenryze
Copy link

TypeScript Version: 2.7.0-dev.201xxxxx

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
interface TypeA {
    test: "test1" | "test2" | "test3"
}

function fn(param: TypeA) {

}

// Check pass
fn({
    test: "test1"
});

// The same object, but passed by object reference
let obj = {
    test: "test1"
};

/**
 * Error:(26, 4) TS2345: Argument of type '{ test: string; }' is not assignable to parameter of type 'TypeA'.
 *   Types of property 'test' are incompatible.
 *   Type 'string' is not assignable to type '"test1" | "test2" | "test3"'.
 */
fn(obj);

Expected behavior:
Check pass
Actual behavior:
I get a TS2345

@ahejlsberg
Copy link
Member

This is working as intended. The argument in the call to fn is contextually typed by TypeA and therefore it is known that the test property has a literal type. However, in the let assignment there is no contextual type, so the type of the test property is widened to string because the property is a mutable location.

It works if you add a type annotation (thus providing a contextual type):

let obj: TypeA = {
    test: "test1"
};

Duplicate of #17363 and others. For a discussion of the widening rules see #10676.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label Nov 26, 2017
@sevenryze
Copy link
Author

Thanks for your promoting reply.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants