microsoft / microsoft/TypeScript

Support custom typeof functions

Abierto
#30,698 14 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
1 d 19 h
PR fusionados (30 d)
117

Descripción

Search Terms

  • custom typeof
  • custom typeof function
  • custom type guard

Suggestion

When using a custom typeof‑like function, I’d like TypeScript compiler to be able to infer the correct type in the scope guarded by the custom typeof‑like function.

Use Cases

I need this to provide proper type information for the type function from Blissfuljs and similar projects.

The current approach requires defining the type(…) function as type(obj: any): string and then doing a type cast every time something is accessed within the if block:

/// <reference types="blissfuljs"/>
declare var something: any;
if ($.type(something) === "array") {
	(something as any[]).forEach(v => {/* stuff */})
}

Examples

type-func.d.ts
/**
 * @param obj The variable to check the type of.
 * @return The result of `typeof obj` or the class name in lowercase for objects.
 *         In the case of numbers, if the value is `NaN`, then the result is `nan`.
 */
declare function type(obj: null): "null";
declare function type(obj: undefined): "undefined";

// This is to ensure that the type system short-circuits when it encounters primitive types.
declare function type(obj: number): "number" | "nan";
declare function type(obj: string): "string";
declare function type(obj: symbol): "symbol";
declare function type(obj: boolean): "boolean";

// Needed to ensure proper return values when wrapper objects are used.
/* tslint:disable:ban-types */
declare function type(obj: number | Number): "number" | "nan";
declare function type(obj: string | String): "string";
declare function type(obj: symbol | Symbol): "symbol";
declare function type(obj: boolean | Boolean): "boolean";
declare function type(obj: Function): "function";
/* tslint:enable:ban-types */

declare function type(obj: any[]): "array";
declare function type(obj: RegExp): "regexp";
declare function type(obj: any): string;
export = type;

example.ts

import type = require("./type-func");
declare var something: any;

if (type(something) === "array") {
	// $ExpectType any[]
	something;
} else if (type(somthing) === "number") {
	// $ExpectType number
	something;
}

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

Comienza con las declaraciones de type-func.d.ts y la reproducción en example.ts del issue; después, inspecciona cómo TypeScript gestiona el narrowing para las comprobaciones de typeof y los type guards definidos por el usuario. Se considera terminado cuando las comparaciones mostradas infieren any[] y number dentro de sus ramas sin casts, y se conservan la salida y el comportamiento existentes de JavaScript.

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
Activo
Claridad
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.