首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript通过带类型检查的构造函数传递字段

Typescript通过带类型检查的构造函数传递字段
EN

Stack Overflow用户
提问于 2020-10-12 19:47:48
回答 1查看 30关注 0票数 0

我试图通过构造函数的对象来传递字段对象:

代码语言:javascript
复制
new Alloy({ name: "foo" })

问题是没有检查类型:

代码语言:javascript
复制
export class Alloy {

    name!: string

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

例如,参见我的第二个测试(is mandatory)不要抛出错误,它应该是:

代码语言:javascript
复制
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);
        })
    });
})
EN

回答 1

Stack Overflow用户

发布于 2020-10-12 20:05:52

问题出在类的定义上。通过添加!s,您告诉TS您知道它不会是未定义的/空的-不是必需的。

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

如果您像这样声明类,那么您将允许TS向您显示问题:

代码语言:javascript
复制
export class Alloy {

    name: string

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

现在,您会得到错误信息,告诉您名称不一定是未定义的,而且data.name也可能是未定义的,因此不能分配给必需的属性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64317289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档