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);
CodePudding user response:
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');
CodePudding user response:
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.