Answer the question
In order to leave comments, you need to log in
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 не считает это ошибкой.
}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question