Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of existing object all as string

Tags:

typescript

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"
}
like image 608
myol Avatar asked Oct 26 '25 02:10

myol


2 Answers

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;
}
like image 89
snak Avatar answered Oct 27 '25 16:10

snak


interface ExampleStringType{
 [key:string]:string;
}
like image 24
bughou Avatar answered Oct 27 '25 17:10

bughou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!