0

In a situation like this (simplified):

    class Order{
        items:{prices:number[],lastUpdate:Date};
    }

I want to have orders not undefined.

    class Order{
        items:{prices:number[],lastUpdate:Date} = {prices:[],lastUpdate:new Date};
    }

does it but I am not sure is the cleanest (lazy) way. What I don't want in this case is create an OrderItem class. Suggestions?

1
  • eeehm... what is the question? if you want an OrderItem without having orders undefined, could you instantiate it with constructor and creating it anywhere with new Order(items: {[], new Date}) Commented Feb 2, 2018 at 14:14

1 Answer 1

1

TypeScript will happily infer types of variables and properties for you, and you only have to correct it if it infers something you don't like.

So you could do this:

class Order {
  items = { prices: [], lastUpdate: new Date };
}

which infers items to be of type { prices: never[]; lastUpdate: Date; }. That's close to what you want but it has no idea that an empty array will hold numbers. So you can then do this:

class Order {
  items = { prices: [] as number[], lastUpdate: new Date };
}

Now you've told it (via type assertion) that the empty array is for numbers, and items is inferred as { prices: number[]; lastUpdate: Date; } as desired.

Hope that helps.

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

1 Comment

Yes! (I think I'm getting a crush on typescript :-)

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.