Search code examples
arraystypescriptinterfacepulumiinfrastructure-as-code

Why would you create a new Array using an interface? (Pulumi)


Brand new to TypeScript and Pulumi/IaC. I'm trying to understand a piece of code where a bunch of key values are composed of a new array using an interface:

import * as cPulumi from "@company/pulumi";

interface TestInterface {
    name: cPulumi.output<string>,
    description: cPulumi.output<string>,
    password: cPulumi.output<string>
}

const allVm = {
    vm1: new Array<TestInterface>(),
    vm2: new Array<TestInterface>(),
    vm3: new Array<TestInterface>()
}

export { allVm }

Is this essentially creating an array for each "vm" where all the values in the index are shaped into TestInterface? I see a bit of code later that pushes multiple objects shaped like the interface into "vm1."


Solution

  • Well you answered your own question, it just creates an empty array, with defined item-type in the generics. The exact same code (assuming the Array constructor didn't get overridden somehow) could be written as:

    const allVm = {
        vm1: [] as TestInterface[],
        vm2: [] as TestInterface[],
        vm3: [] as TestInterface[],
    }
    

    or as

    const allVm: { vm1: TestInterface[], vm2: TestInterface[], vm3: TestInterface[] } = {
        vm1: [],
        vm2: [],
        vm3: [],
    }
    

    It's just that new Array<Type> is easier to read, also it is preferable in projects where type casting as in [] as TestInterface[] is banned by linter rules.

    TS Playground