This has to do with excess property checking and object literal freshness .
(这与多余的属性检查和对象文字新鲜度有关 。)
When is an object literal considered fresh might you ask?
(您可能会问什么时候一个对象文字被认为是新鲜的?)
An object literal is considered fresh when Typescript infers its type for you and there was neither type assertion nor was the object literal assigned to a variable.
(当Typescript为您推断其类型并且既没有类型断言也没有将对象常量分配给变量时,则认为对象常量是新鲜的。)
// using type assertion, this works
data: await createCategory({ id: 555, name: 'sdfsdf', parentId: 55 } as CreateCategoryDto)
In the first case, you assigned it to a variable, so the freshness dissapeared and there was no excess property checking.
(在第一种情况下,您将其分配给变量,因此新鲜度消失了,并且没有多余的属性检查。)
const data = { id: 555, name: 'sdfsdf', parentId: 55 }; // you assigned it to a variable
data1: await createCategory(data)
However, in the second case you passed the object literal directly to the function without assigning it to a variable first, so Typescript infered its type: the object literal is fresh.
(但是,在第二种情况下,您将对象常量直接传递给函数,而没有先将其分配给变量,因此Typescript推断了其类型:对象常量是新鲜的。)
data: await createCategory({ id: 555, name: 'sdfsdf', parentId: 55 }) // this object is fresh
And when that's the case, there's something we call excess property checking, which works as follows: when you try to assign a fresh object literal type T to another type U, and T has properties that aren't in U, Typescript complains.
(在这种情况下,我们称之为多余的属性检查,其工作原理如下:当您尝试将新的对象文字类型T分配给另一个类型U且T具有U中没有的属性时,Typescript抱怨。)
This is useful for detecting misspellings. (这对于检测拼写错误很有用。)
Quoting from the docs:
(从文档引用:)
[...] TypeScript takes the stance that there's probably a bug in this code.
([...] TypeScript认为此代码中可能存在一个错误。)
Object literals get special treatment and undergo excess property checking when assigning them to other variables , or passing them as arguments . (将对象文字分配给其他变量或将其作为参数传递时, 将对其进行特殊处理并进行过多的属性检查。)
If an object literal has any properties that the “target type” doesn't have, you'll get an error [...] (如果对象文字具有“目标类型”所没有的任何属性,则会出现错误[...])
This also produces an error:
(这也会产生一个错误:)
var categoryDto: CreateCategoryDto = { id: 555, name: 'sdfsdf', parentId: 55 }
whereas this doesn't:
(而这不是:)
var categoryDto = { id: 555, name: 'sdfsdf', parentId: 55 }
var test: CreateCategoryDto = categoryDto
The CreateCategoryDto
shape is a contract and just says what the object should contain.
(CreateCategoryDto
形状是一个合同,仅说明对象应包含的内容。)
Object types are covariant in their members (you want a T or a subtype of T), extra properties are insignificant. (对象类型在其成员中是协变的(您需要T或T的子类型),多余的属性无关紧要。)
But there was excess property checking involved due to the object literal being fresh. (但是由于对象文字是新鲜的,因此涉及过多的属性检查。)