Skip to content

Type inference lacking on index signature types #5089

Closed
@alexeagle

Description

@alexeagle

The compiler gives an error on the last line:

function s(p: {[k:string]:string}) {
    console.log(p);
}

let t: {[k:string]:string} = {thing: 'otherthing'};
s(t);

let t2 = {thing: 'otherthing'}; 
s(t2);

Index signature is missing in type '{thing: 'otherthing'}'

Which is very sad since I'm refactoring all of angular to use string index signatures instead of our hacky StringMap (angular/angular#4483)

Activity

danquirk

danquirk commented on Oct 3, 2015

@danquirk
Member

The reason for this rule was because we could not guarantee that t2 did not get additional properties after initialization that would make it invalid for use with s. For example:

let t2 = {thing: 'otherthing'};
t2 = {thing: 'otherotherthing', foo: 1 }
s(t2); // s is going to assume t2.foo is a string though

The rule is that object literals that are contextually typed by a type with an indexer signature then get the index signature pushed into the literals type (this is what happens to t). However, now the code I posted above is an error under the new object literal strictness checks. But the strictness rules only extend so far:

let t2 = {thing: 'otherthing'};
let t3 = {thing: 'otherotherthing', foo: 1 }
t2 = t3;
s(t2); // error
alexeagle

alexeagle commented on Oct 3, 2015

@alexeagle
ContributorAuthor

Okay, thanks for explaining. I'm almost done adding explicit types.

What about this case, where I get an error, it seems like the type narrowing within the type guard should work?

function s(p: {[k:string]:string}) {
    console.log(p);
}

class Foo {}
function l(q: Foo | {[key: string]: any}) {
  if (q instanceof Foo) {
      console.log(q);
  } else {
      s(q);  // <--- still a union, thinks it might be a Foo
  }
}
RyanCavanaugh

RyanCavanaugh commented on Oct 3, 2015

@RyanCavanaugh
Member

We don't yet narrow the else clause on account of instanceof; see #1719

alexeagle

alexeagle commented on Oct 3, 2015

@alexeagle
ContributorAuthor

thanks, world-class support! 💐

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @alexeagle@RyanCavanaugh@danquirk

        Issue actions

          Type inference lacking on index signature types · Issue #5089 · microsoft/TypeScript