Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class with null properties when initializing

Tags:

typescript

I have started a new Next.js project with typescript with npx create-next-app --example with-typescript with-typescript-app (https://github.com/zeit/next.js/tree/master/examples/with-typescript).

How ever when I try to create a class like this:

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

I get the syntax error:

Property 'id' has no initializer and is not definitely assigned in the constructor.ts(2564)

when I add a constructor like this:

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

It works. Why is that and how can I create an object so the properties are null when initializing the class?

The same code is working without the constructor in angular

like image 963
Jonas Avatar asked Jul 27 '26 14:07

Jonas


1 Answers

You can define your properties as optional, with a ? modifier:

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

Now if you initialize a new instance of type "Programm", properties will have undefined value.

like image 153
Jurica Smircic Avatar answered Jul 29 '26 05:07

Jurica Smircic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!