0

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?

2
  • What is the purpose of the type? Since you map it to any you lose type information.. Commented Apr 17, 2019 at 8:48
  • Is Record<keyof Interface, any> a thing you need? Commented Apr 17, 2019 at 8:48

3 Answers 3

1

You can make a special generic type:

type WrapMyType<T, V> = { [key in keyof T]: V };

const control: WrapMyType<IDetail, any> = {
  name: [],
  enabled: [],
};
Sign up to request clarification or add additional context in comments.

Comments

1

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: []
};

Comments

-1

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.