0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.