我试图通过构造函数的对象来传递字段对象:
new Alloy({ name: "foo" })问题是没有检查类型:
export class Alloy {
name!: string
constructor(data: Partial<Alloy>) {
Object.assign<Alloy, Alloy>(this, {
name: data.name!
});
}
}例如,参见我的第二个测试(is mandatory)不要抛出错误,它应该是:
import { Alloy } from "./Alloy"
describe("Alloy", () => {
const defaultParams = {
name: "Foo bar"
}
describe("has a name", () => {
test("is a string", async () => {
const alloy = new Alloy({ ...defaultParams, name: "Foo bar" })
expect(alloy.name).toEqual("Foo bar")
expect(typeof alloy.name === "string").toBeTruthy()
})
// this test is failing
test("is mandatory", async () => {
const t = () => {
const alloy = new Alloy({ ...defaultParams, name: undefined })
};
expect(t).toThrow(TypeError);
})
});
})发布于 2020-10-12 20:05:52
问题出在类的定义上。通过添加!s,您告诉TS您知道它不会是未定义的/空的-不是必需的。
你永远不会得到像这样的运行时错误-因为所有的类型检查都发生在编译时,而不是运行时。
如果您像这样声明类,那么您将允许TS向您显示问题:
export class Alloy {
name: string
constructor(data: Partial<Alloy>) {
Object.assign<Alloy, Alloy>(this, {
name: data.name,
});
}
}现在,您会得到错误信息,告诉您名称不一定是未定义的,而且data.name也可能是未定义的,因此不能分配给必需的属性。
https://stackoverflow.com/questions/64317289
复制相似问题