TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Spurious 'Index signature is missing in type' error when subclassing

Open NoelAbrahams opened this issue 11 years ago • 6 comments

Hi,

TS: 1.4

Not sure that I agree we should have an error here:

interface Indexer {
        [x: string]: number
}

class Base {

 foo() : Indexer {
    return undefined;
 }
}

/*Error: Class 'Foo' incorrectly extends base class 'Base'.
 Types of property 'foo' are incompatible.
 Type '() => { id: number; }' is not assignable to type '() => Indexer'.
 Type '{ id: number; }' is not assignable to type 'Indexer'.
 Index signature is missing in type '{ id: number; }'.
*/  
class Foo extends Base {

 foo() {
    return { id: 10 };
 }
}

NoelAbrahams avatar Feb 02 '15 13:02 NoelAbrahams

I ran into a variation of this with properties and static properties that is affecting me:

interface Indexer {
  [x: string]: number
}

class Base {
  static foo: Indexer;
  bar: Indexer;
}

class Foo extends Base {
  static foo = { id: 10 } // Class 'Foo' incorrectly extends base class 'Base'
  bar = { id: 10 } // Class 'Foo' incorrectly extends base class 'Base'
}

Foo.foo = { id: 10 } // no error (which seems correct)

jbrantly avatar Feb 02 '15 14:02 jbrantly

Seems related. In my case the error goes away when foo is annotated:

 foo() : Indexer {
    return { id: 10 };
 }

One shouldn't have to do this.

NoelAbrahams avatar Feb 02 '15 14:02 NoelAbrahams

This looks to be a duplicate of #1373

ahejlsberg avatar Feb 02 '15 18:02 ahejlsberg

See also http://stackoverflow.com/questions/22077023/why-cant-i-indirectly-return-an-object-literal-to-satisfy-an-index-signature-re

The last piece of the puzzle is that subclass methods are not contextually typed by their base class function signatures.

(aaand Anders referenced issue I was about to link once I found it)

RyanCavanaugh avatar Feb 02 '15 18:02 RyanCavanaugh

The last piece of the puzzle is that subclass methods are not contextually typed by their base class function signatures.

Yes, I see that now. It's all the more confusing because the error message contains information about the mismatch between the base and subclasses. And one is left scratching their head thinking "if the compiler already knows about this, why then is it complaining?!"

I keep getting tripped up by the contextual typing of objects with index signatures. (I feel I've been referred to that SO post before!) The fact that it has taken a long post on StackOverflow kind of hints at the usability issues surrounding this.

Nevertheless it's a very informative response. Thanks!

NoelAbrahams avatar Feb 02 '15 19:02 NoelAbrahams

Can anyone help me with this scenario please

https://stackoverflow.com/questions/44629786/typescript-index-signature-is-missing-in-type-contextual-typing

codermannn avatar Jun 19 '17 14:06 codermannn