Search code examples
typescriptgenericstypestype-conversionstrong-typing

Get Literal types for object keys in typescript dynamically?


I want to get object keys type, here i write a generic for object with keys as string

type GenericInput = {
  [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, error?:string}
}

function PageContent(props: { children: React.ReactNode,inputs:GenericInput,getData:(data)=>void}) {
  const [query,setQuery] = useState<GenericInput>(props.inputs)
  
  const formKeys = Object.keys(query)
getData(query)
}

But I want to pass data such that i get object literal of key type So when that IDE provide auto-completion for keys. Kind of want to convert keys into literal type.

i want to achieve something like that,

 type GenericInput = {
      [key:  Object.keys(query)]:{value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, error?:string}
    }

Solution

  • Typescript Record Generic Type

    To Create an object interface with known keys you can use Record, and, to create an object interface with unknown keys you can use [key: string]: TYPE.

    TO Work with Record and for you question :

    type GenericInputProperties = {
        value: string;
        type: HTMLInputTypeAttribute;
        placeholder: string;
        min?: number;
        max?: number;
        required?: boolean;
        error?: string;
    };
    
    type GenericInput<Keys> = Record<Keys, GenericInputProperties>;
    

    refs :
    Typescript Record
    Typescript Generics

    Enjoy :)