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
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
type in Typescript, but it doesn't allow you to assemble 2 partials back into
, because it can't verify at compile time that all required fields are going to be there. Here is how I solved it with
, 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: "",
      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