Home > Software design >  typescript type: define dictionary-like object type with a certain condition
typescript type: define dictionary-like object type with a certain condition

Time:05-21

How can we define the type that follows the rules below with typescript:

  1. has certain keys and values(say: key1 of srting type and its value as Date)
  2. may (or may not) have any kind of key-value pairs for the rest

image:

{
 "key1": new Date(),
 "otherKey": "any value",
 ...
}

Thanks!

CodePudding user response:

You could use [key: <type>]: <type> to add custom amount to key-value pairs.

const customType: {
    key: Date,
    [key:string]: any
  } = {
    key: new Date(),
    "string": "another value",
    "number": 10
    // [...]
  }
  • Related