1

Let's say I got this interface:

// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}

and I use it here

// FooModel.ts
import IFoo from "./IFoo";

export default class FooModel implements IFoo {
  foo = 'hello';
  bar = 1;

  constructor(_fooModel?: IFoo) {
    if (_fooModel === undefined) return; // <-- this is what I am talking about
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar
  }
}

is there a better (more elegant and readable to be specific) way to reproduce this? I'm mainly talking about the if undefined return statement. Which will apply their default values if it returns, of course.

1
  • 1
    @T. J. Crowder thanks, fixed it Commented May 31, 2020 at 16:07

1 Answer 1

3

I think I'd use a destructured parameter with a default value, like this:

export default class FooModel implements IFoo {
    foo: string;
    bar: number;

    constructor({foo = "hello", bar = 1} : Partial<IFoo> = {}) {
// Prop defaults −−−−^^^^^^^^^−−−−−−^^^                  ^^^^−−−−− overall default
        this.foo = foo;
        this.bar = bar;
    }
}

Playground link

In that example, the default expression isn't evaluated unless it's needed, so even an expensive expression is fine.

That also lets you assign partial IFoos (just foo or just bar). If you don't want that, move the default values into the overal initializer, like this:

    constructor({foo, bar}: IFoo = {foo: "hello", bar: 1}) {

Playground link


FWIW, note that the values in the initializers on the properties in your original code will always be assigned, your constructor is currently effectively:

// Your current code, in effect
constructor(_fooModel?: IFoo) {
    this.foo = 'hello';
    this.bar = 1;
    if (_fooModel === undefined) return;
    this.foo = _fooModel.foo;
    this.bar = _fooModel.bar;
}

That's just fine, but I thought I'd mention it in case there was an expensive expression being used instead.

Sign up to request clarification or add additional context in comments.

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.