I am getting a Typescript warning for the following:
let d: { [key: string]: { [k: string]: boolean } | number[] } = {
blah: [],
};
d["blah"].push(2);
The warning:
This expression is not callable.
Not all constituents of type 'boolean | ((...items: number[]) => number)'
are callable.
Type 'false' has no call signatures. (tsserver 2349)
The code works and if I console.log(d[‘blah’]) I get [2]. Why am I getting the warning? How do I correct it (or ignore it)?
My tsconfig:
{
"compilerOptions": {
"target": "es2015",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
I tried printing to the console and the code works so am confused why the warning if it works
>Solution :
According to your typescript interface you defined key can be either an array of number or an object.
So you should first check if d['blah'] is an array then push the value
interface IObjectType {
[key: string]: {
[k: string]: boolean
} | number[]
}
let d: IObjectType = {
blah: [],
};
if (Array.isArray(d['blah'])) {
d["blah"].push(2);
}