title: Type-safe pattern for modifying individual properties in Typescript interface
body: <p>I have a TypeScript interface that includes properties that are a type union, and I have a predefined way of modifying the value of the property at runtime that narrows the type.  As a simple example:</p>
  <pre><code>interface WideFoo {
    x: string | RegExp;
    y: number;
  }
  
  interface NarrowFoo {
    x: RegExp;
    y: number;
  }
  
  function narrow(wf: WideFoo): NarrowFoo {
    return {
      x: wf.x instanceof RegExp ? wf.x : new RegExp(wf.x),
      y: wf.y,
    };
  }
  
  function f(nf: NarrowFoo) {
    if (nf.x.test(&quot;Hello&quot;)) { ... }
  }
  
  declare const wf: WideFoo;
  f(narrow(wf));
  </code></pre>
  <p>The <code>narrow</code> function makes a new object and copies over the property, converting it if necessary.  This is easy when I know exactly what properties to copy, and the interface is small.  If the interface is large or complex, this approach scales poorly.</p>
  <p>I can't have type-directed runtime code (that's a core TS principle), so I don't think I can automatically pick which properties need to be converted.  I don't want to use casts or type assertions, because I want the code to fail loudly if a new property is added to the interface that needs to be converted at runtime.</p>
  <p>How can I write <code>narrow</code> so that properties that won't be modified are copied/preserved, while properties that are of the &quot;wide&quot; type are converted and correctly limited to the narrower type?  It's OK if the solution only works for flat (one-deep) objects, rather than recursively.</p>