它会编译,因为你正在做一个断言。你基本上是在说“相信我,TypeScript 编译器,这是正确的类型”。这完全绕过了检查。
如果您的对象满足类型,则无需进行断言。TypeScript 中的接口通过实际检查对象是否满足接口来工作,而不是它显式地扩展/实现接口。
interface ResponseBody {
foo1: number;
foo2: string;
foo3: boolean;
}
function doSomething(value: ResponseBody) {
console.log("Ok");
}
因此:
// This will work
doSomething({ foo1: 0, foo2: "zero", foo3: false });
// This will not work
// Argument of type '{ foo1: number; foo2: string; }' is not assignable to parameter of type 'ResponseBody'.
// Property 'foo3' is missing in type '{ foo1: number; foo2: string; }'.
doSomething({ foo1: 0, foo2: "zero" });
// This will not work
// Type 'number' is not assignable to type 'string'.
doSomething({ foo1: 0, foo2: 1, foo3: false });
// This will work
const r1: ResponseBody = { foo1: 4, foo2: "four", foo3: true };
// This will not work
// Type 'string' is not assignable to type 'number'.
const r2: ResponseBody = { foo1: '4' };
// This will not work
// Type '{ foo1: number; }' is not assignable to type 'ResponseBody'.
// Property 'foo2' is missing in type '{ foo1: number; }'.
const r3: ResponseBody = { foo1: 4 };
所以基本答案是:删除<Foo>
. 你不应该需要它。
现在,如果您传递给的对象doSomething
来自其他地方并且属于any
类型,TypeScript 无法进行检查。所以会失败。在这些情况下,您需要添加断言,让 TypeScript 知道您知道自己在做什么。但这是因为对象(及其字段)在编译时是未知的,因此 TypeScript 根本无法检查。