Search code examples
typescript

In Typescript, can one define that a parameter has to be a field of a object that might be undefined?


I have an interface that has an optional field with another interface. Can I create a function that expects a field of that second interface?

interface A {
  b?: B;
  c: B;
}

interface B {
  y?: string;
}

function outputfield<T extends object, K extends keyof T, K2 extends keyof T[K]>
  (model: T, field1: K, field2: K2): void {
  console.log(model, field1, field2);
}

const a: A = { c: {} }

outputfield(a, 'b', 'y');
// works

outputfield(a, 'c', 'y');
// Argument of type 'string' is not assignable to parameter of type 'never'.

How do I have to change the annotation of outputfield?


Solution

  • This should work I believe:

    function outputfield<
      T extends object,
      K extends keyof T,
      K2 extends keyof NonNullable<T[K]>
    >(model: T, field1: K, field2: K2): void {
      console.log(model, field1, field2);
    }