0

我有这个打字稿代码:

interface Foo {
  foo1: string,
  foo2: number,
  foo3: boolean
}


const v = <Foo>{foo1: '4'};

这可以编译 - 除非对象中存在所有 3 个字段,否则如何防止它编译?现在只有一个字段存在。

这是我的用例/基本原理: https ://gist.github.com/ORESoftware/8d02fb30c53c19f6b38bddbc96da2475

但如果你这样做:

const v : Foo = {foo1: '4'};

然后它不会编译。如果你这样做:

  const v = <Foo>{x: '4'};

那不会编译。

4

1 回答 1

1

它会编译,因为你正在做一个断言。你基本上是在说“相信我,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 根本无法检查。

于 2018-11-15T22:53:55.537 回答