Type checking by interface in TypeScript: how to determine if an object matches an interface?
Hi everyone! I just started learning TypeScript and ran into a problem. I have a `User` interface and a function that receives data from an API. I need to check if the received object matches this interface.
Here's my code:
```typescript
interface User {
id: number;
name: string;
email: string;
}
function processData(data: unknown) {
// How to check that data is a User?
if (data instanceof User) { // Error: 'User' refers only to a type, but is being used as a value here
console.log(data.name);
}
}
```
I understand that `instanceof` doesn't work with interfaces because they are erased at runtime. But how then can I check that the object contains all the required fields with the correct types? I've seen that you can use custom type guards
No answers yet.
Log in to leave an answer