microsoft / microsoft/TypeScript

Array of object unions not working as expected

Abierto
#59,970 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Needs More Info
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

🔎 Search Terms

"array of object unions", "array union narrowing", "union narrowing", "object union operator in"

🕗 Version & Regression Information
  • This changed between versions 5.2.2 and the latest 5.6.2
⏯ Playground Link

Playground

💻 Code
interface EntryBase {
    /**
     * Type info...
     */
    type?: 'default' | 'declaration' 
    /**
     * Output base info...
     */
    output?: string
    /**
     * Format base info...
     */
    format?: string
    /**
     * Name base info...
     */
    name?: string
}

interface PluginsDefault {
    /**
     * Esbuild plugin info...
     * 
     * @default undefined
     */
    esbuild?: Record<string, unknown>
}

interface EntryDefault extends EntryBase {
    /**
     * Input default info...
     */
    input: string
    /**
     * Name default info...
     */
    name?: string
    /**
     * Plugins default info...
     * 
     * @default undefined
     */
    plugins?: PluginsDefault
}

interface PluginsDeclaration {
    /**
     * Dts plugin info...
     * 
     * @default undefined
     */
    dts?: Record<string, unknown>
}

interface EntryDeclaration extends EntryBase {
    /**
     * Declaration info...
     */
    declaration: string
    /**
     * Plugins declaration info...
     * 
     * @default undefined
     */
    plugins?: PluginsDeclaration
}

type EntriesOptions = EntryDefault | EntryDeclaration


const options: EntriesOptions[] = [
    /**
     * Honestly here I would expect TypeScript to be smart enough
     * to automatically inffer types based on only one required property (`input`)
     * and picks correct interfaces and all descriptions but I can assume
     * that this is more complex than it sound 
     */
    {
        input: './src/index.ts', 
        output: './dist/index.mjs', 
        // no description or autocomplete 
        plugins: { esbuild: {} },
        // no description or autocomplete 
        name: 'default name',
        type: 'default'
    },

    /**
     * Also again only one required property `declaration' so it would be nice if 
     * TypeScript could automatically infer the whole interface correctly
     */ 
    {
        declaration: './src/types.ts',
        output: './dist/types/index.d.ts',
        format: 'esm',
        // no description or autocomplete 
        plugins: { dts: {} },
        // no description or autocomplete 
        name: 'declaration name',
        type: 'declaration'
    }
]

/**
 * I searched a lot on the net and came across this example https://stackoverflow.com/questions/73155261/how-to-narrow-down-a-generic-type-based-on-object-property-type
 * where `jcalz`describes and gives an example how to narrow the types based on object keys, 
 * but I guess this is the current working solution and doesn't work in all cases, 
 * I also wonder how to do it when the key property is optional and not specified in object?
 */

type ExtractOnProp<T, K extends keyof T, V> =
    T extends unknown ? V extends T[K] ?
    { [P in keyof T]: P extends K ? T[P] & V : T[P] }
    : never : never

type EntriesOptionsPerProp = ExtractOnProp<EntryDefault, 'type', 'default'> |  ExtractOnProp<EntryDeclaration, 'type', 'declaration'> 

function defineConfig(options: EntriesOptionsPerProp[]): EntriesOptionsPerProp[] {
    return options
} 

defineConfig([
    {
        input: './src/index.ts', 
        output: './dist/index.mjs',
        plugins: { esbuild: {} },
        name: 'default name',
        type: 'default'
    },
    {
        declaration: './src/types.ts',
        output: './dist/types/index.d.ts',
        format: 'esm',
        plugins: { dts: {} },
        name: 'declaration name',
        type: 'declaration'
    },
    // does not work if `type` is not defined
    {
        input: './src/index.ts', 
        output: './dist/index.mjs',
        plugins: { esbuild: {} },
        name: 'default name',
    },
])
🙁 Actual behavior

Hi, as discussed in previous issue #56082 and the merged PR, it seems like this area could use some internal improvements.

When we have multiple interfaces that extend the base interface, then the types are not picked up correctly when defining a new array of object unions.

Also, properties from the object do not get description information or offer correct auto-completion which can be confusing.

🙂 Expected behavior

I expect it to offer the correct auto-completion for each object and give the right information when I hover over a property to see the type or description of what that option does.

Additional information about the issue

I mentioned some examples and expectations of behavior in the playground.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con el Playground enlazado y el ejemplo de defineConfig de un array de uniones de objetos, comparando TypeScript 5.2.2 con 5.6.2. Investiga el comportamiento reportado de narrowing, autocompletado y hover para las entradas con y sin la propiedad type. Se considera terminado cuando cada miembro de la unión proporciona las descripciones de propiedades y el autocompletado esperados, incluido el caso en que se omite type.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Error
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.