Home > Net >  Type of existing object all as string
Type of existing object all as string

Time:06-15

I have an object type which has properties of different types

type ExampleType = {
  one: string
  two: boolean
  three: 'A' | 'Union'
}

Is there a shorthand way to explain this same type but with all properties as string?

type ExampleStringType = {
  one: string
  two: string
  three: string
}

In the docs I see some intrinsic string manipulation types but nothing for setting all properties as string. I assume it must be possible. I was imagining something like

const value: AllString<ExampleType> = {
  one: "string"
  two: "string"
  three: "string"
}

CodePudding user response:

You can use keyof to get keys of a specified type, and you can map them to string.

type AllString<T> = {
  [key in keyof T]: string;
}

CodePudding user response:

interface ExampleStringType{
 [key:string]:string;
}

CodePudding user response:

If your keys and values can be any strings, you can use Record

type YourType = Record<string, string>;

Read more about the Record utility type here.

  • Related