0

The below describes what I'd like to do:

interface Customer {
    name: string;
    age: number;
}

const getCustomer = () => {
    return {
        name: 'bob',
        age: 42
    }
}

export const getValue = (key: keyof Customer): typeof Customer[key] => {
    const customer = getCustomer();
    return customer[key];
};

but the TS compiler doesn't like the line typeof Customer[key]. I could make this any or string | number, but I should be able to get the type from this. For example, if I write:

getValue('name') what does it return? You know without any runtime information, it returns a string. What if I write getValue('age')? A number of course. getValue(someInputVal as any) might return string or number, but all of this is perfectly available at compile time. So - is there a way to get this from typescript?

1 Answer 1

1

you can slightly rewrite your function to use a generic:

export function getValue<T extends keyof Customer>(key: T): Customer[T] {
    const customer = getCustomer();
    return customer[key];
};

what this is essentially saying is that getValue should only accept an argument that extends the keys of the Customer interface and it will return the associated type with that T key from the interface.

here is a ts playground link with the example solution i suggested

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.