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:
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.
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.
Most helpful comment
Note that you can usually get away with a type definition instead because it works similarly to an object literal type.
TS Playground