Home > database >  Add type annotation for property value shorthand
Add type annotation for property value shorthand

Time:10-14

MergedObject can hold an arbitrary number of MyClass instances variable name to MyClass instance key value pairs, where the property name is the variable name e.g Obj1 and the value is the MyClass instance. How do I add a type annotation for MergedObject?

class MyClass {
  a: string;
  constructor(a: string) {
    this.a = a
  }
}

const Obj1 = new MyClass('one')
const Obj2 = new MyClass('two')

const MergedObject = {
  Obj1, Obj2
}

CodePudding user response:

If the contents of MergedObject change over time, you're using MergedObject like a Map, so you might consider actually using a Map (in this case, a Map<string, MyClass>):

const MergedObject = new Map<string, MyClass>(
    Object.entries({
        Obj1,
        Obj2,
    })
);

Playground link

If its contents don't change over time (it's a static construct), there's no need to apply a type annotation to it, TypeScript will infer the type just fine from the initializer:

const MergedObject = {
    Obj1,
    Obj2,
};

Playground link

That also has the advantage that it has strongly-typed keys ("Obj1" | "Obj2", not string). But if you wanted to loosen it, you could use Record<string, MyClass>.

CodePudding user response:

One possible type annotation would be an object with a string index signature containing MyClass values.

const MergedObject: Record<string, MyClass> = {
  Obj1, Obj2
}

Playground

  • Related