Home > Mobile >  How to use interface as type of object?
How to use interface as type of object?

Time:08-04

if u see the code. to make argument accept json object. it need define with type built-in typescript data type. how to pass interface as type for json object? it keep repetitive in my code. to make duplicate what implement in interface.

interface Credential {
  username: string,
  password: string
};

type Credentials = {
  username: string,
  password: string
}

class User {
  username: string;
  password: string;

  constructor(credential: Credentials) {
    this.username = credential.username;
    this.password = credential.password
  }
}

CodePudding user response:

In your example you are trying to define Credential interface that is already provided by global typescript types (check here). Because if this conflict it acts strangely in your case.

I strongly recommend renaming that interface to another name and then you will avoid any conflicts. Rewriting global types with the same name can cause unexpected behaviour. If you rename it, you can just one interface without additional type and everything will work.

  • Related