2

I'm a rather newbie for TypeScript.

Can anyone explain the meaning of this TypeScript code snippet?

function MappableMixin<T extends Constructor<Model<MappableTraits>>>(Base: T) {

Code link is here

Thanks.

3
  • Which part of the statement is unclear? Commented Feb 14, 2022 at 13:41
  • It's a function (mixin) that returns a class of a specific generic type. Do you have a more specific question? Commented Feb 14, 2022 at 13:41
  • mostly <T extends Constructor<Model<MappableTraits>>>(Base: T) Commented Feb 14, 2022 at 13:42

1 Answer 1

5

Let's break this down bit by bit:

function MappableMixin(Base: T)

The function takes a generic type T a its argument

function MappableMixin<T extends Something>(Base: T)

The <TypeArgument> term just between the function name and the (params) term tells typescript to expect that the return type of this function of of type TypeArgument. In the case that TypeArgument is of the form T extends Something, it means that the returned value will be a type that extends Something, meaning it has all the properties of Something. Essentially in this case, MappableMixin takes in some argument, and returns that argument with the extra properties of the type Something.

<Model<MappableTraits>>

This is a generic type with a type argument. So for example, you may have a type Model, which accepts a type as an argument:

interface Model<T> {
  thing1: string;
  thing2: T
}

In the case of using <Model<MappableTraits>>, Model<T> would have the type

interface Model<MappableTraits> {
  thing1: string;
  thing2: MappableTraits
}

So Constructor<Model<MappableTraits>>> follows this same pattern, just 2 layers deep.

So the whole phrase means that MappableMixin is a function that returns an extended version of the value you gave it. The extension is specifically of the type Constructor<Model<MappableTraits>>>, which is a 2-layer typescript generic.

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

1 Comment

hi, Seth, thank you very much.

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.