0

I have an interface like:

interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}

I then have some method to get these properties out as requested:

async getOktaUserProperty(key: keyof OktaUser): Promise<any> {
        // Do some stuff

        return oktaUser[key];
}

Is there any way I can avoid using any in the return, I could manually do Promise<number | string | boolean> but makes it a little cumbersome to maintain.

Any ideas?

Thanks.

1 Answer 1

1

Try this playground link. It uses several features of TypeScript including generics and index types.

interface OktaUser {
    someId: number;
    email: string;
    email_verified: boolean;
}

function getOktaUserProperty<TKey extends keyof OktaUser>(key: TKey): OktaUser[TKey] {
    const x: OktaUser = {
        someId: 10,
        email: 'foo',
        email_verified: true,
    };

    return x[key]
}

const y = getOktaUserProperty('email'); // string
const z = getOktaUserProperty('someId'); // number
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome that works - but I have no idea what it means lol So are we declaring a generic function, with some TKey being a property of OktaUser, - however at that stage why is the extends keyword needed?
@userMod2 It takes some time to get the hang of it. There are detail in the index types link. Reading that section and understanding what it means will take you a long way to becoming a TypeScript expert.

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.