Nadiely Jade
Nadiely Jade

Reputation: 255

declare all property in object the same type in typescript?

I know I can declare type for object like so in typescript:

interface PersonType {
    fname: string
    lname: string
}
const person: PersonType = {fname:"John", lname:"Doe"};

but is there a way to declare all the property have the string type? I don't want to specify any property key and type.

Upvotes: 1

Views: 1467

Answers (2)

If you still need to use only interface, you can do next:

interface PersonType {
    [index: string]: string
}

const person: PersonType = {fname:"John", lname:"Doe"};

Here you can find the docs

Upvotes: 1

Aleksey L.
Aleksey L.

Reputation: 38046

You could use Record<Keys,Type> utility:

Constructs a type with a set of properties Keys of type Type

const foo: Record<string, string> = { fname: "John", lname: "Doe" };

Playground


Record is an alias for:

type Record<K extends string | number | symbol, T> = { [P in K]: T; }

Upvotes: 0

Related Questions