microsoft / microsoft/TypeScript

Suggestion: Use typeof of declaration to define its type

Abierto
#32,694 9 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

Search Terms

  • infer variable declaration
  • typeof declaration
  • using typeof on current expression
  • apply modifier to declaration
  • generic declarations

Suggestion

I would like to use current declaration type for modifying type of variable, I'm creating, e.g.:

const foo: Readonly<typeof var> = {
  bar: 'baz',
}

Maybe, there is a better syntax, that I couldn't think of.

Use Cases

Typescript infer rather narrow type from variable declaration by default, which is a good thing. Sometimes we want to widen it, so it can fit into our interfaces. Mostly, it can be done by simply declaring a variable of certain type. But sometimes, it's useful to create some object along the way and somehow extend it's inferred type(some libraries can export very complicated generic types, so explicitly writing them could be a pain)

My specific use case was caused by reselect library, when I tried to reuse some selectors.

// typeof selectors is (selector1ReturnType | selector2ReturnType | selector3ReturnType)[]
const selectors = [
  state => someSelector1(state),
  state => someSelector2(state),
  state => someSelector3(state),
]

But this array of selectors couldn't be used in createSelector function, cause it is expecting a tuple of selectors, to correctly infer type of arguments of selector function. I tried to use as const on my declaration, but it leaded to another error, cause createSelector expects a mutable tuple(it's only a type thing, not that it really mutates the selectors, but I'm afraid, this is a really common case in all library typings, not to mark it's arguments as readonly). I also found a solution for creating tuples with function, but I don't like the fact, that static typings require some(even tiny) runtime overhead, also the solution is not generic.
For now, I ended up with something like this, using Writable type from this docs:

const selectorsConst = [
  state => someSelector1(state),
  state => someSelector2(state),
  state => someSelector3(state),
] as const
const selectors: Writable<typeof selectorsConst> = selectorsConst as any

But this solution is not pretty also. I wanted it to look like this:

const selectorsConst: Writable<typeof var> = [
  state => someSelector1(state),
  state => someSelector2(state),
  state => someSelector3(state),
] as const

Or even something like this(but this is out of scope of this issue):

const selectorsConst: Tuple<typeof var> = [
  state => someSelector1(state),
  state => someSelector2(state),
  state => someSelector3(state),
]

Examples

Making a Readonly, Partial, Writable, etc. object:

const foo: Partial<typeof var> = {
  bar: {
    baz: 'value',
  },
}
foo.bar.baz = 'new value' // Error: Object is possibly 'undefined'

Unifying object values types:

interface MyClass {
  bar?: string;
  baz?: string;
}
const foo: {
  [key in keyof typeof var]: MyClass;
} = {
  firstEntry: { bar: 'bar' },
  secondEntry: { baz: 'baz' },
}

Checklist

My suggestion meets these guidelines:

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

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

No se nombran archivos, pruebas ni puntos de entrada. Empieza revisando cómo representa TypeScript las consultas typeof, las anotaciones de tipos en declaraciones, los mapped types y la inferencia de tuplas; la tarea estará completa cuando la propuesta tenga un diseño acordado y las pruebas correspondientes del compilador.

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

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.