在打字稿中输入注释
Type annotations in typescript
interface Test {
name: string;
age: number;
}
const subjectObj = {
name: "Harhsit Singh",
age: 17,
height: "6'1",
};
const testObj: Test = subjectObj; //? NO ERROR
const testObj2: Test = {
name: "Harhsit Singh",
age: 17,
height: "6'1", //! ERROR
};
我创建了一个如图所示的 interface test
和一个名为 subjectObj
的测试对象,它包含的属性比 test
类型包含的属性更多。
现在我已将我的 subjectObj 分配给 test
类型的常量 testObj,然后用相同的方式声明另一个常量 testObj2键入 test
并为其分配相同的对象,但这次使用与 subjectObj.
具有相同结构的新对象对其进行初始化
但现在它给了我一个 'height' does not exist in type 'test'
的错误,但是当我通过 subjectObj 作为对 testObj 的引用时没有给出任何错误 尽管它还包含 属性 高度 .
我不知道为什么会这样,所以需要一些详细的解释。
Excess property checking 仅在您传递对象字面量时发生——当您传递类型时,您 运行 发现 TS 从不检查 确切类型 , 并假定您的意思是具有过多类型的对象。
这真的是因为 TS 嵌入了 JS 文化。否则,在 TS 中针对 JS 接口编写代码真的很难。
interface Test {
name: string;
age: number;
}
const subjectObj = {
name: "Harhsit Singh",
age: 17,
height: "6'1",
};
const testObj: Test = subjectObj; //? NO ERROR
const testObj2: Test = {
name: "Harhsit Singh",
age: 17,
height: "6'1", //! ERROR
};
我创建了一个如图所示的 interface test
和一个名为 subjectObj
的测试对象,它包含的属性比 test
类型包含的属性更多。
现在我已将我的 subjectObj 分配给 test
类型的常量 testObj,然后用相同的方式声明另一个常量 testObj2键入 test
并为其分配相同的对象,但这次使用与 subjectObj.
但现在它给了我一个 'height' does not exist in type 'test'
的错误,但是当我通过 subjectObj 作为对 testObj 的引用时没有给出任何错误 尽管它还包含 属性 高度 .
我不知道为什么会这样,所以需要一些详细的解释。
Excess property checking 仅在您传递对象字面量时发生——当您传递类型时,您 运行 发现 TS 从不检查 确切类型 , 并假定您的意思是具有过多类型的对象。
这真的是因为 TS 嵌入了 JS 文化。否则,在 TS 中针对 JS 接口编写代码真的很难。