0

Ordering of keys is guaranteed on a (modern) literal Javascript object:

>> const sophie = {name: 'Sophie', age: 17, color: 'black'}
>> Object.keys(sophie)
['name', 'age', 'color']

Is it also guaranteed for Javascript/Typescript class constructor args?

class Cat {
  constructor(
    public name:  string,
    public age:   number,
    public color: string
  ) {}
}

>> const sophie = new Cat('Sophie', 17, 'black')
>> Object.keys(sophie)
['name', 'age', 'color'] <- is this order guaranteed?
Sasgorilla
  • 2,403
  • 2
  • 29
  • 56
  • 1
    Note that the feature you're talking about here, where constructor arguments are copied to properties of the same names as the constructor parameters, is called [*parameter properties*](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties) – jcalz Jan 06 '23 at 02:51
  • There is no *documented guarantee* that the parameter property order will always match the insertion order (and therefore determine the key order); TypeScript doesn't have an up-to-date language specification so there's no obvious source of truth for that anyway. I suspect that, in practice, the order will be stable, but that's a guess and not authoritative by any means. Does that fully address your question? If so I could write it up as an answer; if not, what am I missing? – jcalz Jan 06 '23 at 03:14
  • Yep @jcalz that's definitely the question I was asking ... too bad of course there's no definitive answer at the current time. What about this [ConstructorParameters](https://stackoverflow.com/a/73457773/4185992) thing? Does that typed tuple not imply the ordering is guaranteed? – Sasgorilla Jan 06 '23 at 13:57
  • A side question it appears to me is why does this order matters? – Alejandro Jan 06 '23 at 14:05
  • @Alejandro here's [my real question](https://stackoverflow.com/questions/75032035/how-can-i-clone-a-typescript-class-instance-while-modifying-selected-properties). If I can rely on the parameter property ordering I think I can solve that one. – Sasgorilla Jan 06 '23 at 14:13
  • 1
    @Sasgorilla: No, `ConstructorParameters` tells you the parameter list accepted when you call the constructor, which doesn't have anything in general to do with what properties exist on an instance of the class. – jcalz Jan 06 '23 at 15:29

0 Answers0