N
N
Nikolay Matyushkin2020-05-10 16:51:22
typescript
Nikolay Matyushkin, 2020-05-10 16:51:22

What should an object look like when the types intersect?

Hello.

There are custom types, one of them uses type intersection:

export type UserInfoType = {
   name: string,
   login: string,
   age: number | string,
   gender: string
};

export type UserType = {
    [key: string]: UserInfoType;
} & {
    city: string;
    country: string;
};


What is the point? I get an object from the server, where the n-th number of users (objects) is always different and there are always city and country properties. Type:

const users: UserType = {
   "Anna": {
      name: "Anna",
      login: "Ann_90",
      age: 28,
      gender: female
   },
   "Tony": {
      name: "Tony",
      login: "ttt_comeback",
      age: 25,
      gender: male
   },
   "Lanessa": {
      name: "Lanessa",
      login: "Lana_142",
      age: 35,
      gender: female
   },
   city: Tampa,
   country: USA,
}


But, when this data arrives at the client, the TS swears at a type mismatch. Those. it is not possible to synchronize data from the server and the type that I wrote. Plz tell me what's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Dvoryanov, 2020-07-29
@Devilz_1

Something tells me this might work.

type UsersValues = {
    [key: string]: string | number;
};

type UserType = {
  [key: string]: UsersValues | string;
};

A
Aetae, 2020-05-15
@Aetae

This type cannot be specified directly. You can infer the type using a padding function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question