我在VSCode中使用VSCode,我想知道为什么当我创建一个Thing
类型的对象或坚持使用接口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
}
发布于 2022-08-31 03:08:20
这种行为是由于类型断言。
<Thing>{}
和{} as Thing
都是类型断言,它们告诉编译器执行比通常更少的严格类型检查。
如问题中所示,编译器仍然会发现重叠问题,使用表单{} as unknown as Thing
可以进一步忽略这些问题。
要确保强类型检查,请使用以下形式:
const t: Thing = {}
导致此错误:
类型‘Thing’中缺少以下属性: id,name。
发布于 2022-02-22 13:08:47
错误非常明显,在Thing
和{ bad: string }
之间没有overvap。
空对象没有任何错误,因为存在重叠:{}
https://stackoverflow.com/questions/71221415
复制相似问题