microsoft / microsoft/TypeScript

Non‑`void` returning assertion functions

Abierto
#40,562 11 comentarios 134 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

  • assertion function non-void return type
  • assertion function non-void return
  • assertion function generic return
  • assertion function custom return

Suggestion

A way to type a function that is both an assertion function and returning a value that is not void.

Use Cases

This is necessary to correctly type Jest’s expect(…) matchers, which have a generic return type of R.

Examples

declare const expect: <T>(actual: T): JestMatchers<T>;

type JestMatchers<T> = JestMatchersShape<
	Matchers<void, T>,
	Matchers<
		Promise<void>,
		T extends PromiseLike<infer U>
			? U
			: Exclude<T, PromiseLike<any>>
	>
>;

type JestMatchersShape<TNonPromise extends {} = {}, TPromise extends {} = {}> = {
	resolves: AndNot<TPromise>;
	rejects: AndNot<TPromise>;
} & AndNot<TNonPromise>

type AndNot<T> = T & { not: T };

interface Matchers<R, T = {}> {
	toBe<E>(expected: E): R & (asserts T is E);
}

declare const foo: unknown;
expect(foo).toBe("foo");
foo; // $ExpectType "foo"
// Some typings for engine262's Completion Record handling:
type UnwrapNormalCompletion<T>
	= unknown extends T ? Value | undefined
	: T extends NormalCompletion<infer V>
		? (unknown extends V ? Value | undefined : V)
	: T extends Completion ? never
	: T;

/** @see https://tc39.es/ecma262/#sec-returnifabrupt */
export declare function ReturnIfAbrupt<T>(completion: T):
	(UnwrapNormalCompletion<T>)
	& (asserts completion is UnwrapNormalCompletion<T>);

/** @see https://tc39.es/ecma262/#sec-returnifabrupt-shorthands */
export { ReturnIfAbrupt as Q };

/**
 * The type signature is the same, but `AssertNormalCompletion` causes an error to be thrown at runtime
 * if `argument` is an AbruptCompletion, whereas `ReturnIfAbrupt` gets replaced with code that causes
 * the caller to return the AbruptCompletion by engine262's build system:
 *
 * @see https://tc39.es/ecma262/#sec-returnifabrupt
 * @see https://tc39.es/ecma262/#sec-returnifabrupt-shorthands
 */
declare function AssertNormalCompletion<T>(completion: T):
	(UnwrapNormalCompletion<T>)
	& (asserts completion is UnwrapNormalCompletion<T>);
export { AssertNormalCompletion as X };

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 de implementación ni pruebas. Empieza revisando el manejo existente de TypeScript para las funciones de aserción y los ejemplos de matchers de Jest y completion records. Se considera terminado cuando se admitan funciones de aserción con valores de retorno genéricos que no sean void, conservando al mismo tiempo el estrechamiento de tipos demostrado.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.