Z
Z
zorro32021-01-09 19:21:49
typescript
zorro3, 2021-01-09 19:21:49

Is it possible to describe an object that can have any keys?

I have a type such as "Animal" and any keys can come to this object, but the value of these keys is always String.
For example, for one response, I get the following object:

General: {
  name: "test",
  example:  {
      breed: "test",
      eyes: "test"
    }
}

For the next one:
General: {
  name: "test",
  example:  {
      something: "test"
      somethingElse: "test"
      someOtherField: "test"
    }
}

Is there any way to describe this object?
type Animal {
  // how i can describe this object?
}

type General {
  name: String
  example: Animal
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-01-12
@bingo347

type Animal = {
  [key: string]: string;
};

Basically the syntax is:
type Animal = {
  [<любое имя>: <тип ключей>]: <тип значений>;
};
The name must be a valid identifier, why is it needed TS - I xs, but without it
the type of keys must be a subtype string | number | symbol, moreover, there are troubles with symbol, there is only a union of specific symbols
value type - any type, but must not intersect with explicit types fields,
explicit fields must be up to universal
. In general, the standard library has utilities of the Record type with two generic arguments - the type of keys and the type of values, moreover, it does not have troubles with symbol:type Animal = Record<string, string>;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question