初始化时属性为空的TypeScript类

pbwdgjma  于 2023-06-24  发布在  TypeScript
关注(0)|答案(3)|浏览(293)

我用npx create-next-app --example with-typescript with-typescript-apphttps://github.com/zeit/next.js/tree/master/examples/with-typescript)的typescript启动了一个新的Next.js项目。
当我尝试创建一个类时:

export class Programm {
    id: string;
    name: string;
    thumbnailUrl: string;
}

语法错误:
Property 'id' has no initializer and is not definitely assigned in the constructor.ts(2564)
当我像这样添加一个构造函数时:

constructor(id: string, name: string, thumbnailUrl: string) {
    this.id = id;
    this.name = name;
    this.thumbnailUrl = thumbnailUrl;
}

为什么会这样呢?我怎样才能创建一个对象,使得在初始化类时属性为空呢?
同样的代码在没有angular中的构造函数的情况下也能正常工作

xu3bshqb

xu3bshqb1#

您可以使用?修饰符将属性定义为可选属性:

export class Programm {
     id?: string;
     name?: string;
     thumbnailUrl?: string;
}

现在,如果你初始化一个新的“Programm”类型的示例,属性将有undefined值。

whlutmcx

whlutmcx2#

我想你可以按照以下步骤->跟随@ Jurica Smircic先生的解决方案->定义初始值

constructor(id: string, name: string, thumbnailUrl: string) {
    this.id = id || '' ;
    this.name = name || '';
    this.thumbnailUrl = thumbnailUrl || '';
}

堆栈中有很多关于为什么不应该使用null或undefined的讨论。他们总是鼓励通过构造函数或在对象初始化过程中定义初始值。例如空对象。为了更好地理解,您可以查看这些Q&A线程。谢谢

wgmfuz8q

wgmfuz8q3#

正如您所问的,如果您希望初始化时的值为空而不是未定义,您可以这样做:

export class Programm {
    id: string | null = null;
    name: string | null = null;
    thumbnailUrl: string | null = null;
}
var programm = new Programm()
console.log(programm)
>>> Programm: { "id":null, "name":null, "thumbnailUrl":null }

相关问题