microsoft / microsoft/TypeScript

Can we cut down on `Object.assign` overloads?

Aperta
#28,323 5 commenti 5 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Needs Proposal Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

We can convert unions into intersections (thanks @jcalz!), and we can model variadic args pretty well, so I figured I'd try to model Object.assign with a single overload. Here's what I came up with:

// Maps elements of a tuple to contravariant inference sites.
type MapContravariant<T> = {
    [K in keyof T]: (x: T[K]) => void
}

type TupletoIntersection<T, Temp = MapContravariant<T>> =
    // Ensure we can index with a number.
    Temp extends Record<number, unknown>
        // Infer from every element now.
        ? Temp[number] extends (x: infer U) => unknown ? U : never
        : never;

declare function assign<T extends object, Rest extends object[]>(
    x: T,
    ...xs: Rest
): T & TupletoIntersection<Rest>;

Unfortunately this doesn't quite give the right results on the following:

let asdf = assign({x: "hello"}, Math.random() ? {x: "hello"} : {z: true });

Currently the type of asdf is:

| ({ x: string; } & { x: string; z?: undefined; })
| ({ x: string; } & { z: boolean; x?: undefined; })

What a beautiful type! Unfortunately you can see that the second element of the union tries to intersect types with conflicting properties for x which is nonsense.

Additionally, @weswigham pointed out that this really won't work for the case where you started off with just a plain array whose elements are eventually spread into Object.assign.

I do wonder if there's anything better we can do here.

Guida per i contributori

Apri la guida per i contributori

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.

Direzione di ricerca

L’issue non indica file, test o punti di ingresso. Inizia riproducendo il tipaggio assign proposto e gli esempi di union e array con spread dell’issue, quindi segui la modellazione esistente di Object.assign nel type checker di TypeScript e nelle dichiarazioni della libreria standard. Il lavoro è completo quando è disponibile un approccio revisionato che gestisca questi casi senza intersezioni in conflitto.

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

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
20/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.