How can I narrow down a value in a function that takes in a key and a value

38 views Asked by At

I'm trying to create a function which can take a key of a type and a value corresponding to that key. Then I want to do something when I'm looking at a specific key. My specific use case for this is a Table component I've built in React that iterates through an Objects entries and passes the key and value into a separate function and I want to provide the ability to override this safely.

I've simplified a bit and implemented this. I have the type User and a function that prints the name contained within the user details. However value.name is not being narrowed and cannot be accessed.

type User = {
    details: {
        name: string;
    };
    account: {
        status: boolean;
    }
}

const printName =  <K extends keyof User>(key: K, value: User[K]) => {
    if (key === 'details') {
        console.log(value.name); // Doesn't work
    }
}

const user: User = {
    details: {
        name: 'Bob'
    },
    account: {
        status: true
    }
}

printName('details', user.details);

The code above produces this type error:

Property 'name' does not exist on type '{ name: string; } | { status: boolean; }'.
Property 'name' does not exist on type '{ status: boolean; }'.(2339)

Typescript Playground Link

0

There are 0 answers