Skip to content

Failure to infer subtype of string despite perfect literal match #19363

Closed
@axefrog

Description

@axefrog

TypeScript Version: 2.6.0-insiders20171013 and 2.5.3

Code

interface Foo  {
  '@type': 'foo/bar';
}

class Bar<T extends Foo> {
  constructor (public value: T) { }
}

function create<T extends Foo> (value: T): Bar<T> {
  return new Bar(value);
}

function main (): Bar<Foo> {
  const value = {
    '@type': 'foo/bar'
  };
  return create(value); // ERROR
}

Expected behavior:

No errors.

Actual behavior:

Argument of type '{ '@type': string; }' is not assignable to parameter of type 'Foo'.
  Types of property ''@type'' are incompatible.
    Type 'string' is not assignable to type '"foo/bar"'.
const value: {
    '@type': string;
}

Clearly I've hardcoded the correct literal. TypeScript should not be inferring that my hardcoded literal is any old string, and should recognize that it matches the string subtype described in the interface.

Interestingly, this works:

function main (): Bar<Foo> {
  return create({
    '@type': 'foo/bar'
  });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions