typescripttypescript-generics

TypeScript generic methods with access to SubObject Key when it's possibly undefined


I have generic method, for get field from object inside other object

function myGenericMethod<T, K extends keyof T, S extends keyof T[K]>(obj: T, key?: K, subkey?: S) {
    
}

But when object is possibly undefined or null TypeScript warn me on key S

myGenericMethod(myEmployee, 'position', 'id');


Argument of type '"id"' is not assignable to parameter of type 'undefined'.ts(2345)

Example Interfaces

interface IPosition{
    id: number,
    name: string
}

interface IEmployee{
    id : number;
    name? : string;
    position? : IPosition;
}

const myEmployee : IEmployee = {
    id: 1,
    name: "Jhon",
    position: 
    { 
        id : 1, 
        name: "Waiter"
    }
}

Its work, but compiller warn me. How to write this code correct. If i make position field not undefined error is gone.


Solution

  • You can make use of TypeScript's NonNullable to make sure that your subkey is valid only when your key references a non null or undefined value.

    function myGenericMethod<
      T,
      K extends keyof T,
      S extends keyof NonNullable<T[K]>,
    >(obj: T, key?: K, subkey?: S) {
      // your implementation
    }