打字稿通过类型检查通过构造函数传递字段

时间:2020-10-12 11:47:48

标签: javascript typescript

我正在尝试将字段对象传递给构造函数的对象:

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);
        })
    });
})

1 个答案:

答案 0 :(得分:0)

问题出在您的班级定义中。通过添加!,您将告诉TS您知道它不会是不确定的/为空-并不是必需的。

您将永远不会遇到这样的运行时错误-因为所有类型检查都在编译时发生,而不是在运行时发生。

如果您声明这样的类,则将允许TS向您显示问题:

export class Alloy {

    name: string

    constructor(data: Partial<Alloy>) {
        Object.assign<Alloy, Alloy>(this, {
            name: data.name,
        });
    }
}

现在您会收到错误消息,告诉您不能保证未定义名称,而且data.name也可以未定义,因此无法分配给必需的属性。