myol
myol

Reputation: 9838

Type of existing object all as string

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"
}

Upvotes: 3

Views: 595

Answers (3)

Son Nguyen
Son Nguyen

Reputation: 1767

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.

Upvotes: 0

snak
snak

Reputation: 6703

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;
}

Upvotes: 2

bughou
bughou

Reputation: 152

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

Upvotes: 1

Related Questions