Skip to content

Type inference for constant objects with string literal types #32139

Closed
@ghost

Description

Hi!

Let's say that I have this code:

interface Greeter {
    hello: 'world'
}

function hello() {
    const first: Greeter = {
        hello: 'world'
    };

    const obj = {
        hello: 'world'
    };

    const second: Greeter = obj;
}

For the first object the compiler can infer type of hello as a string literal type and outputs no errors. However, for the second object can't infer this, although obj is a constant object, and throws an error.

It would be nice to have automatic inference here. For example, in Flow types are inferred here automatically and the same code passes type checks without errors.

Addition: specifying the string type literal explicitly helps:

const obj = {
    hello: 'world' as 'world'
}

but makes the code look verbose.

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions