Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

A better way to use mixins ?

Aperta
#3,338 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
38/100
Tipo di issue
Documentazione
Chiarezza
Abbastanza chiara
Stato di attività
Ferma
Stack tecnologico
typescript
Ambito
documentation

Direzione di ricerca

Inizia dalla pagina sui mixin di TypeScript Handbook collegata nell’issue e rivedi l’esempio Playground fornito. Valuta come il pattern proposto e i suoi limiti dichiarati si inseriscono nella documentazione esistente, quindi aggiorna la guida sui mixin con un’alternativa accurata e avvertenze chiare.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

The document gives some examples on how to use mixin here: https://www.typescriptlang.org/docs/handbook/mixins.html

However the 2 proposed solutions has issues:

  • the first one prevent us from having private/protected members, and may generate quite a lot of type deduction error in the function.
  • the second is not that great regarding to type safety.

I think we have a better solution to use mixin, that could be added to the documentation:

class Base {}

// declare the added properties outside of the mixin function
abstract class Mixin {}

class K extends mix(Base, Mixin) { }

Such generic function could be implemented like this:

const MixSrc = Symbol();

type Mix<
            Base  extends          new(...args:any[])=>any,
            Mixin extends abstract new(...args:any[])=>any,
        > = Omit<Base & Mixin, "new"> & (new(...args:ConstructorParameters<Base>) => (InstanceType<Base> & InstanceType<Mixin>))

function mix<
                Base  extends          new(...args:any[]) => any,
                Mixin extends abstract new(...args:any[]) => any
            >(base: Base, mixin: Mixin): Mix<Base, Mixin> {

    class _ extends base {}

    const static_props = Object.getOwnPropertyDescriptors(mixin);
    delete static_props.prototype;
    delete static_props.name;
    Object.defineProperties( _, static_props );

    ((_ as any)[MixSrc] ??= []).push(mixin);

    const hasInstance = mixin[Symbol.hasInstance];
    Object.defineProperty(mixin, Symbol.hasInstance, {
        value: function (instance: any) {
            if( instance.constructor[MixSrc].includes(this) )
                return true;
            return hasInstance.call(this, instance);
        },
        writable: false,
    });

    const instance_props = Object.getOwnPropertyDescriptors(mixin.prototype);
    // @ts-ignore
    delete instance_props.constructor;
    Object.defineProperties( _.prototype, instance_props );

    return _ as any; // well...
}

Playground Link

There are 2 limitations of this method:

  • This may not work if Mixin inherit from another class ( though you could just call mix for each of the Mixin bases ).
  • This will not work if Mixin has private # properties.

If we have private properties, we can do something like:

abstract class Mixin {
     // declare the public/protected interface here
}

type ExcludeProtected<T> = {[K in keyof T]: T[K]}
function addMixin<...>(base): Mix<Base, Mixin> {
      return class _ extends base implements ExcludeProtected<Mixin> {
             // implements Mixin methods here...
             // can't guarantee the protected interface (due to TS limitations).
      } as any;
}

But then Mixin must not inherit from another class.

Lingua principale
TypeScript
Stelle
2.6k
Fork
1.5k
Merge medio
2g 12h
PR unite (30g)
8

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di microsoft/TypeScript-Website

Tutte le issue di microsoft/TypeScript-Website

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.