1

I have multiple objects in my app. For example:

interface Recipe {  
  title: string,  
  ingredients: []  
  creator: string,  
  // ...  
}

interface Vendor {  
  name: string
  address: Address  
  // ...  
}

The user should have the ability to create objects that can accept any of these interfaces for example:

interface Event<T> {  
  date: Date(),  
  type: T // This should be of type Recipe or Vendor object for example.  
}
  1. What is the proper way to define this?
  2. How would I then find out which object the user passed?

Thank You!

3
  • Hi @Agata! I'm not sure, what do you mean "the proper way to define this"? You already defined correctly an Event which can accept a Generic type. Would you like to force type nly to be one of "Recipe" or "Vendor"? Commented Apr 27, 2020 at 11:58
  • Yes. I am also not clear on how to identify which object the user passed? Commented Apr 27, 2020 at 12:03
  • You could use Unions. Example Commented Apr 27, 2020 at 12:03

1 Answer 1

1

In order to know which type the user passed, you need to use discriminated unions.

To do so, you should:

  1. Augment the interfaces adding a kind or type, or whatever you like, property in order to discriminate between them:
interface Recipe {  
  type: 'Recipe',
  title: string,  
  ingredients: []  
  creator: string,  
  // ...  
}

interface Vendor {  
  type: 'Vendor',
  name: string
  address: Address  
  // ...  
}
  1. Define an union type including the available objects
type Entity /* or whatever */ = Recipe | Vendor;

Now TS can understand which specific interface is used given the type property

  1. Define the Event given the union type
interface Event<T extends Entity> {  
  date: Date,  
  type: T['type'], // If you need only the type
  object?: T
}

const event: Event<Recipe> = {
  date: Date,
  type: 'recipe',
  object: recipe
}

function <T extends Entity>(event: Event<T>) {
  switch (event.type) {
    // ...
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Where do I declare the type. Can you also give me an example how would I instantiate this interface?
You can declare the type after the interfaces or just before them, it doesn't matter. I'll update the answer with an Event example.
You're welcome. If an answer satisfy you, please accept it so other users will know it worked.

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.