Siddharth Shyniben
Siddharth Shyniben

Reputation: 772

Dynamically add types to interface in typescript

This is totally not necessary, but I want to know if types can be assigned dynamically to interfaces.

Suppose I have the following interface:

interface UserAuth {
    username: string;
    password: string;
    auth0: SomeOtherAuthInterface;
}

Obviously, if auth0 is set, then there's no need for a password (maybe there is but let's just assume there's not) and vice versa. Is there a way to type that?

Upvotes: 0

Views: 288

Answers (2)

Siddharth Shyniben
Siddharth Shyniben

Reputation: 772

You could use the Omit utility type to choose which ones you need:

interface Auth { 
    username: string;
    password: string;
    auth0: SomeOtherAuthInterface;
}

type Auth0 = Omit<Auth, "password">
type BasicAuth = Omit<Auth, "auth0">

Upvotes: 0

cefn
cefn

Reputation: 3321

If you label the distinct cases with a distinct value of a literal member, then you can compose a discriminated union, in which different 'variants' of your type can be distinguished by the compiler using a type guard.

interface UserData {
  kind:"basic"
  username: string;
}

interface UserAuth {
  kind:"authenticated",
  username: string;
  password: string;
  auth0: "something";
}

type UserRecord = UserData | UserAuth

function (record:UserRecord){
  if(record.kind==="basic"){
    console.log(record.username) 
    //console.log(record.auth0) this would be an error 
  }
  else if(record.kind==="authenticated"){
    console.log(record.username) 
    console.log(record.password) 
    console.log(record.auth0) 
  }
}

See this page for more information https://basarat.gitbook.io/typescript/type-system/discriminated-unions

Upvotes: 1

Related Questions