N
N
Nikita2020-11-21 21:43:51
typescript
Nikita, 2020-11-21 21:43:51

How can I force typescript to only allow code to execute if two types are strictly equal to each other?

Let's say we have code like this:

class UserModel {
    // Все те поля, что есть у UserDTO 
    password: string;
} // Модель User в БД. 

class UserDTO {
    email: string;
}

const getUser = async (email: string): Promise<UserDTO> => {
     const user = await db.find(email); // Тип возращаемого объекта является UserModel

      return user; // UserModel не эквивалентен UserDTO, но TypeScript не считает это ошибкой.
}


How to prevent typescript from allowing returning an object equivalent to this type as a UserDTO, except that this object also has additional fields that are not described in UserDTO.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2020-11-21
@Aetae

Answer: don't use typescript.
Structural typing is the essence of typescript. You can google all sorts of vile crutches, but they are not a panacea and will fail at the most crucial moment.

L
Lynn "Coffee Man", 2020-11-21
@Lynn

The easiest way is to make the types unequal. For example like this:

class UserModel {
    email: string;
    password: string;
}

class UserDTO {
    protected __guard: never; // добавляем фиктивное поле
    email: string;
}

const getUser = async (email: string): Promise<UserDTO> => {
  const user = await db.find(email);
  return user; // Ошибка, как заказывали
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question