Reputation: 12357
I'm using an intermediary step for creating a type that has property keys that must be the same as the keys of a specified interface
// 1. Create Interface
interface IDetail {
name: string;
enabled: boolean;
}
// 2. Create a 'type' that has properties that match the properties of an interface
type DetailType = {
[key in keyof IDetail]: any
}
// 3. Apply the type to an object literal
const control: DetailType = {
name: [],
enabled: []
}
I repeat this pattern quite often, and I'm wondering is there a way to generalize the 2nd step - possibly using generics?
Upvotes: 0
Views: 82
Reputation: 16127
You can make a special generic type:
type WrapMyType<T, V> = { [key in keyof T]: V };
const control: WrapMyType<IDetail, any> = {
name: [],
enabled: [],
};
Upvotes: 1
Reputation: 37594
If you don't want to lose the types you can use this approach
type DetailType<T> = { [key in keyof T]: T[key] };
const control: DetailType<IDetail> = {
name: [], // must be string
enabled: [] // must be boolean
}
Upvotes: -1
Reputation: 10137
Well you can just make your type generic:
interface IDetail {
name: string;
enabled: boolean;
}
type Generic<T> = { [key in keyof T]: any };
const controlGeneric: Generic<IDetail> = {
name: [],
enabled: []
};
Upvotes: 1