1

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

1
  • You didn't create new Project(). Commented May 2, 2022 at 14:48

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.