https://pulumi.com logo
#general
Title
# general
b

best-xylophone-83824

08/12/2019, 1:14 PM
Just sharing some typesafety tricks I am learning along the way. Lets say you create resources in a table-driven way. Resources have
*Args
argument some fields of which are mandatory and it just happens so that you want to some mandatory fields come from default set and some to be specified in each row of your "table". There is a
Partial<T>
type in Typescript, but it doesn't allow you to assemble 2 partials back into
T
, because it can't verify at compile time that all required fields are going to be there. Here is how I solved it with
PartialExcept<T,E>
, where it makes T's fields all partial, except for those listed in `E`:
Copy code
type PartialExcept<T,E extends keyof T> = Partial<T> & Pick<T,E>;
👍 1
Example use:
Copy code
const vpc = new gcp.compute.Network("main", {
        autoCreateSubnetworks: false,
});



// our table of networks to create
const networks : {[name : string]: PartialExcept<gcp.compute.SubnetworkArgs, 'ipCidrRange'>} = {
   "gke01-london": {
      ipCidrRange: "10.0.1.0/26",
      privateIpGoogleAccess: true,
   }
};


// default values 
const defaultSubnetArgs: PartialExcept<gcp.compute.SubnetworkArgs, 'region'|'network'> = {
        region: "eu-west2", // london
        network: vpc.selfLink,
        privateIpGoogleAccess: false,
};

let results : { [name : string]: gcp.compute.Subnetwork } = {};

for (const name in networks) {
     results[name] = new gcp.compute.Subnetwork(name, {...defaultSubnetArgs, ...networks[name]})  // compiler can verify that second argument matches desired interface, even if individual values it was assembled from dont
};