1

Say I have a typescript interface:

interface IOriginal {
    aaa: string;
    bbb: boolean;
}

... and now say that I want to create a similar interface with identical keys but different values (in my specific case the values are derived using the Reducer generic from Redux, but I'd like to keep the answer quite general):

import { Reducer } from "redux";
interface IDerived{
    aaa: Reducer<string>;
    bbb: Reducer<boolean>;
}

Question: how can I generate IDerived directly from IOriginal without explicitly retyping all the key-value pairs (violating DRY and having two places to update stuff)? If these were objects I could do sth like this:

const derived = original;
for(var key in derived) derived[key] = Reducer(original[key]);

... but I'm not sure if there are equivalent tools when dealing with types/interfaces.

1 Answer 1

4

You're looking for a mapped type:

type IDerived = { [K in keyof IOriginal]: Reducer<IOriginal[K]> };
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.