'Typescript not addressing missing properties
I am using TypeScript in VSCode and I am wondering why I am not getting an error when I create an object of type Thing or adhering to interface IThing
code.ts
type Thing = {
id: number;
name: string;
};
const t1 = <Thing>{}; // No error for missing properties
const t2 = {} as Thing; // No error for missing properties
const t3 = <Thing>{ bad: 'wrong ' }; // intellisense returns ERROR below
const t4 = { bad: 'wrong ' } as Thing; // intellisense returns ERROR below
interface IThing {
id: number;
name: string;
}
const it1 = <IThing>{}; // No error for missing properties
const it2 = {} as IThing; // No error for missing properties
const it3 = <IThing>{ bad: 'wrong ' }; // intellisense returns IERROR below
const it4 = { bad: 'wrong ' } as IThing; // intellisense returns IERROR below
// ERROR: "Conversion of type '{ bad: string; }' to type 'Thing' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ bad: string; }' is missing the following properties from type 'Thing': id, name"
// IERROR: "Conversion of type '{ bad: string; }' to type 'IThing' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ bad: string; }' is missing the following properties from type 'IThing': id, name"
.eslintrc.json
{
"parser": "@typescript-eslint/parser",
"settings": {
"react": {
"version": "detect"
}
},
"plugins": [
"@typescript-eslint",
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"env": {
"es6": true,
"browser": true,
"jest": true,
"node": true
},
"rules": {
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/no-empty-function": 0,
"@typescript-eslint/explicit-function-return-type": 0,
"@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/explicit-member-accessibility": 0,
"@typescript-eslint/indent": 0,
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-var-requires": 0,
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/no-non-null-assertion": 0,
"@typescript-eslint/no-unused-vars": [
2,
{
"argsIgnorePattern": "^_"
}
],
"no-console": [
1,
{
"allow": ["warn", "error"]
}
]
},
"root": true
}
Solution 1:[1]
The error is quite explicit, You have no overvap between Thing and { bad: string }
You don't have any error with the empty object because there is an overlap : {}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matthieu Riegler |
