Typescript: index signature is missing for type

Created on 27 Aug 2019  路  4Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.4.0-dev.201xxxxx


Search Terms:
index signature is missing in type ...

Code

interface A { name: string; }

function testFn (param: {[key: string]: string}) {
    return param;
}

let testA: A = {name: 'Xavier'};
let testB: { name: string; } = {name: 'Xavier'};

testFn(testA); <- Error: index signature is missing
testFn(testB); <- Working fine

Expected behavior:
Allow to pass testA to testFn.
Actual behavior:
Throw an error
Playground Link:
https://stackblitz.com/edit/missing-index-in-type-demo?file=index.ts
Related Issues:

Working as Intended

Most helpful comment

Note that you can usually get away with a type definition instead because it works similarly to an object literal type.

interface A { name: string; }
type C = { name: string; }

function testFn (param: {[key: string]: string}) {
    return param;
}

let testA: A = {name: 'Xavier'};
let testB: { name: string; } = {name: 'Xavier'};
let testC: C = {name: 'Xavier'};

testFn(testA); // throw an error 
testFn(testB); // same structure but this works
testFn(testC); // Works like object literal type.

TS Playground

All 4 comments

This is working as intended. Object literal types have implicit index signatures---interfaces do not.

If you search "_index signature is missing for type_" issue #32263 appears in the first 10 results, and it should point you to relevant PR's and issues.

Note that you can usually get away with a type definition instead because it works similarly to an object literal type.

interface A { name: string; }
type C = { name: string; }

function testFn (param: {[key: string]: string}) {
    return param;
}

let testA: A = {name: 'Xavier'};
let testB: { name: string; } = {name: 'Xavier'};
let testC: C = {name: 'Xavier'};

testFn(testA); // throw an error 
testFn(testB); // same structure but this works
testFn(testC); // Works like object literal type.

TS Playground

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dlaberge picture dlaberge  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

blendsdk picture blendsdk  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

seanzer picture seanzer  路  3Comments