Charles
Charles

Reputation: 11758

How to set default property value in typescript

Is it possible to have the name set by its default value with this code?

interface ProjectInterface {
  id: string;
  name?: string;
}

class Project implements ProjectInterface {
  id: string;
  name?: string = 'default name';
}

const project: Project = {id: 'hello'};

console.log(project.name);

https://playcode.io/892621

Upvotes: 1

Views: 1052

Answers (2)

Anubhav Gupta
Anubhav Gupta

Reputation: 212

I don't think so. I think you can't provide default values for interfaces or type aliases as they are compile time only and default values need runtime support.

Upvotes: 0

Juulloo
Juulloo

Reputation: 111

Once you instantiate a new Project the name will take it's default value. For instantiation to work you first need to definitively assign the id in a constructor or with a default value:

class Project implements ProjectInterface {
    id: string;
    name?: string = 'default name';
 
    constructor(id: string) {
        this.id = id;
    }
}

const project: Project = new Project('hello');

Upvotes: 2

Related Questions