microsoft / microsoft/TypeScript

Import type over generic argument

Aperta
#31,090 12 commenti 44 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Awaiting More Feedback Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.4k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

Search Terms

import type, generic, module string type

Suggestion

To allow for giving a generic argument as an import() type's argument, something like
function <Mod extends string>(obj: unknown, modPath: Mod): obj is import(Mod);

Use Cases

Would allow generic functions that type inference from any module path string literal to the type exported by that module. This is helpful for encapsulating good module loading practices. For instance, in a large AMD application I work on, we need to manage the application footprint by not loading modules that aren't needed for the current execution path. There are a number of utility functions we could write around handling modules to support good behavior on this front.

Examples

One of the signatures of AMD's require() could be typed as:
function require<Mod extends string>(path: Mod): import(Mod);
This actually does work today if that declaration is put in a .d.ts file and skipLibCheck is set to true. If a string literal is passed, the return type is inferred from the path; if non-literal, the return type is any. In fact, if this worked but disallowed anything other than a module path, it would be super handy for typo avoidance. I'm pretty sure what's happening now is accidental, though, since any more complex use yields a "string literal expected" error on the import type.

Likewise, I'm pretty sure a really useful signature for define() could be done with a mapped type and tuple typed-rest params, something like:

type ImportsOf<Paths extends string[]> = { P in keyof Paths: import(Paths[P]) };
function define<Paths extends string[]>(paths: Paths, callback: (...args: ImportsOf<Paths>)=>void);

Specifically, the function I wanted to write with this was a type-narrowing instanceof check over a module path. Given a module that exports a constructor:

function isModuleInstance<Mod extends string>(obj: unknown, path: Mod): obj is InstanceType<import(Mod)> {
    const modValue = require(path);
    return modValue && obj instanceof modValue
}

If the module for a constructor hasn't been loaded, we can assume no object has been constructed by it, so this technique is very handy for keeping down the module load footprint in applications with lots of modules.

A question for discussion would be the value of an import-type on a non-literal argument, or a non-module argument for that matter. My initial impression is if the import() type can't be resolved, it should evaluate to never and produce an error just like import('some_garbage_string_i_made_up')". That might require the type checker to be given a stricter bound than "extends string", though. If necessary, a user-visible built-in type that means "a string representing a known module" seems like it might be useful in lots of contexts.

Checklist

My suggestion meets these guidelines:

  • [X ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [X ] This wouldn't change the runtime behavior of existing JavaScript code
  • [X ] This could be implemented without emitting different JS based on the types of the expressions
  • [X ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [Seems like it to me] This feature would agree with the rest of TypeScript's Design Goals.

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

Inizia riproducendo gli esempi generici di import() in un file .d.ts con skipLibCheck abilitato, inclusi i percorsi di modulo letterali e non letterali. Confronta il comportamento attuale con le firme richieste e definisci cosa deve accadere per gli argomenti non risolvibili o che non sono moduli; il lavoro è completo quando i casi previsti vengono accettati con i tipi inferiti attesi e i casi non validi continuano a essere diagnosticati in modo appropriato.

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
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.