Reputation: 3732
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.
Upvotes: 1
Views: 120
Reputation: 30999
You're looking for a mapped type:
type IDerived = { [K in keyof IOriginal]: Reducer<IOriginal[K]> };
Upvotes: 4