简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM