expectTypeOf
WARNING
En tiempo de ejecución, esta función no realiza ninguna operación. Para habilitar la verificación de tipos, asegúrate de usar la bandera --typecheck.
- Tipo:
<T>(a: unknown) => ExpectTypeOf
not
- Tipo:
ExpectTypeOf
Puedes negar todas las aserciones utilizando la propiedad .not.
toEqualTypeOf
- Tipo:
<T>(expected: T) => void
Este matcher verifica si los tipos son exactamente idénticos. No fallará si dos objetos tienen valores diferentes pero el mismo tipo. Sin embargo, sí fallará si a un objeto le falta una propiedad.
import { expectTypeOf } from 'vitest';
expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>();
expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 });
expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 });
expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>();toMatchTypeOf
- Tipo:
<T>(expected: T) => void
Este matcher comprueba si el tipo esperado extiende el tipo proporcionado. Es diferente de toEqual y se asemeja más a toMatchObject() de expect. Con este matcher, puedes verificar si un objeto "se ajusta" a un tipo.
import { expectTypeOf } from 'vitest';
expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 1 });
expectTypeOf<number>().toMatchTypeOf<string | number>();
expectTypeOf<string | number>().not.toMatchTypeOf<number>();extract
- Tipo:
ExpectTypeOf<ExtractedUnion>
Puedes usar .extract para refinar tipos y realizar pruebas adicionales.
import { expectTypeOf } from 'vitest';
type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T };
interface CSSProperties {
margin?: string;
padding?: string;
}
function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
return {};
}
const cssProperties: CSSProperties = { margin: '1px', padding: '2px' };
expectTypeOf(getResponsiveProp(cssProperties))
.extract<{ xs?: any }>() // extrae un miembro de la unión que coincide con la forma proporcionada
.toEqualTypeOf<{
xs?: CSSProperties;
sm?: CSSProperties;
md?: CSSProperties;
}>();
expectTypeOf(getResponsiveProp(cssProperties))
.extract<unknown[]>() // extrae un array de una unión
.toEqualTypeOf<CSSProperties[]>();WARNING
Si no se encuentra ningún tipo en la unión, .extract devolverá never.
exclude
- Tipo:
ExpectTypeOf<NonExcludedUnion>
Puedes usar .exclude para eliminar tipos de una unión y realizar pruebas adicionales.
import { expectTypeOf } from 'vitest';
type ResponsiveProp<T> = T | T[] | { xs?: T; sm?: T; md?: T };
interface CSSProperties {
margin?: string;
padding?: string;
}
function getResponsiveProp<T>(_props: T): ResponsiveProp<T> {
return {};
}
const cssProperties: CSSProperties = { margin: '1px', padding: '2px' };
expectTypeOf(getResponsiveProp(cssProperties))
.exclude<unknown[]>()
.exclude<{ xs?: unknown }>() // o simplemente .exclude<unknown[] | { xs?: unknown }>()
.toEqualTypeOf<CSSProperties>();WARNING
Si no se encuentra ningún tipo en la unión, .exclude devolverá never.
returns
- Tipo:
ExpectTypeOf<ReturnValue>
Puedes usar .returns para extraer el tipo de valor de retorno de una función.
import { expectTypeOf } from 'vitest';
expectTypeOf(() => {}).returns.toBeVoid();
expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2]);WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
parameters
- Tipo:
ExpectTypeOf<Parameters>
Puedes extraer los argumentos de una función con .parameters para realizar aserciones sobre sus tipos. Los parámetros se devuelven como un array.
import { expectTypeOf } from 'vitest';
type NoParam = () => void;
type HasParam = (s: string) => void;
expectTypeOf<NoParam>().parameters.toEqualTypeOf<[]>();
expectTypeOf<HasParam>().parameters.toEqualTypeOf<[string]>();WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
TIP
También puedes usar el matcher .toBeCallableWith para una aserción más expresiva.
parameter
- Tipo:
(nth: number) => ExpectTypeOf
Puedes extraer un argumento de función específico usando .parameter(number) para realizar otras aserciones sobre él.
import { expectTypeOf } from 'vitest';
function foo(a: number, b: string) {
return [a, b];
}
expectTypeOf(foo).parameter(0).toBeNumber();
expectTypeOf(foo).parameter(1).toBeString();WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
constructorParameters
- Tipo:
ExpectTypeOf<ConstructorParameters>
Puedes extraer los parámetros del constructor como un array de valores y realizar aserciones sobre ellos con este método.
import { expectTypeOf } from 'vitest';
expectTypeOf(Date).constructorParameters.toEqualTypeOf<
[] | [string | number | Date]
>();WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
TIP
También puedes usar el matcher .toBeConstructibleWith para una aserción más expresiva.
instance
- Tipo:
ExpectTypeOf<ConstructableInstance>
Esta propiedad proporciona acceso a los matchers que se pueden aplicar a una instancia de la clase proporcionada.
import { expectTypeOf } from 'vitest';
expectTypeOf(Date).instance.toHaveProperty('toISOString');WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
items
- Tipo:
ExpectTypeOf<T>
Puedes obtener el tipo de elemento de un array con .items para realizar aserciones adicionales.
import { expectTypeOf } from 'vitest';
expectTypeOf([1, 2, 3]).items.toEqualTypeOf<number>();
expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf<string>();resolves
- Tipo:
ExpectTypeOf<ResolvedPromise>
Este matcher extrae el valor resuelto de una Promise, permitiendo realizar otras aserciones sobre él.
import { expectTypeOf } from 'vitest';
async function asyncFunc() {
return 123;
}
expectTypeOf(asyncFunc).returns.resolves.toBeNumber();
expectTypeOf(Promise.resolve('string')).resolves.toBeString();WARNING
Si se utiliza en un tipo que no es una promesa, devolverá never, impidiendo el encadenamiento con otros matchers.
guards
- Tipo:
ExpectTypeOf<Guard>
Este matcher extrae el tipo de guarda (por ejemplo, v is number), permitiendo realizar aserciones sobre él.
import { expectTypeOf } from 'vitest';
function isString(v: any): v is string {
return typeof v === 'string';
}
expectTypeOf(isString).guards.toBeString();WARNING
Devuelve never si el valor no es una función de guarda, impidiendo el encadenamiento con otros matchers.
asserts
- Tipo:
ExpectTypeOf<Assert>
Este matcher extrae el tipo de aserción (por ejemplo, assert v is number), permitiendo realizar aserciones sobre él.
import { expectTypeOf } from 'vitest';
function assertNumber(v: any): asserts v is number {
if (typeof v !== 'number') {
throw new TypeError('Nope !');
}
}
expectTypeOf(assertNumber).asserts.toBeNumber();WARNING
Devuelve never si el valor no es una función de aserción, impidiendo el encadenamiento con otros matchers.
toBeAny
- Tipo:
() => void
Con este matcher puedes comprobar si el tipo proporcionado es any. Si el tipo es demasiado específico, la prueba fallará.
import { expectTypeOf } from 'vitest';
expectTypeOf<any>().toBeAny();
expectTypeOf({} as any).toBeAny();
expectTypeOf('string').not.toBeAny();toBeUnknown
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es unknown.
import { expectTypeOf } from 'vitest';
expectTypeOf().toBeUnknown();
expectTypeOf({} as unknown).toBeUnknown();
expectTypeOf('string').not.toBeUnknown();toBeNever
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es never.
import { expectTypeOf } from 'vitest';
expectTypeOf<never>().toBeNever();
expectTypeOf((): never => {}).returns.toBeNever();toBeFunction
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es una function.
import { expectTypeOf } from 'vitest';
expectTypeOf(42).not.toBeFunction();
expectTypeOf((): never => {}).toBeFunction();toBeObject
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es un object.
import { expectTypeOf } from 'vitest';
expectTypeOf(42).not.toBeObject();
expectTypeOf({}).toBeObject();toBeArray
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es Array<T>.
import { expectTypeOf } from 'vitest';
expectTypeOf(42).not.toBeArray();
expectTypeOf([]).toBeArray();
expectTypeOf([1, 2]).toBeArray();
expectTypeOf([{}, 42]).toBeArray();toBeString
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es un string.
import { expectTypeOf } from 'vitest';
expectTypeOf(42).not.toBeString();
expectTypeOf('').toBeString();
expectTypeOf('a').toBeString();toBeBoolean
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es boolean.
import { expectTypeOf } from 'vitest';
expectTypeOf(42).not.toBeBoolean();
expectTypeOf(true).toBeBoolean();
expectTypeOf<boolean>().toBeBoolean();toBeVoid
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es void.
import { expectTypeOf } from 'vitest';
expectTypeOf(() => {}).returns.toBeVoid();
expectTypeOf<void>().toBeVoid();toBeSymbol
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es un symbol.
import { expectTypeOf } from 'vitest';
expectTypeOf(Symbol(1)).toBeSymbol();
expectTypeOf<symbol>().toBeSymbol();toBeNull
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es null.
import { expectTypeOf } from 'vitest';
expectTypeOf(null).toBeNull();
expectTypeOf<null>().toBeNull();
expectTypeOf(undefined).not.toBeNull();toBeUndefined
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado es undefined.
import { expectTypeOf } from 'vitest';
expectTypeOf(undefined).toBeUndefined();
expectTypeOf<undefined>().toBeUndefined();
expectTypeOf(null).not.toBeUndefined();toBeNullable
- Tipo:
() => void
Este matcher comprueba si el tipo proporcionado puede ser null o undefined.
import { expectTypeOf } from 'vitest';
expectTypeOf<undefined | 1>().toBeNullable();
expectTypeOf<null | 1>().toBeNullable();
expectTypeOf<undefined | null | 1>().toBeNullable();toBeCallableWith
- Tipo:
() => void
Este matcher verifica que la función proporcionada puede ser llamada con un conjunto específico de parámetros.
import { expectTypeOf } from 'vitest';
type NoParam = () => void;
type HasParam = (s: string) => void;
expectTypeOf<NoParam>().toBeCallableWith();
expectTypeOf<HasParam>().toBeCallableWith('some string');WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
toBeConstructibleWith
- Tipo:
() => void
Este matcher asegura que se puede crear una nueva instancia con un conjunto específico de parámetros de constructor.
import { expectTypeOf } from 'vitest';
expectTypeOf(Date).toBeConstructibleWith(new Date());
expectTypeOf(Date).toBeConstructibleWith('01-01-2000');WARNING
Si se utiliza en un tipo que no es una función, devolverá never, impidiendo el encadenamiento con otros matchers.
toHaveProperty
- Tipo:
<K extends keyof T>(property: K) => ExpectTypeOf<T[K]>
Este matcher verifica si una propiedad existe en el objeto proporcionado. Si existe, también devuelve el mismo conjunto de matchers para el tipo de esta propiedad, permitiendo encadenar aserciones.
import { expectTypeOf } from 'vitest';
const obj = { a: 1, b: '' };
expectTypeOf(obj).toHaveProperty('a');
expectTypeOf(obj).not.toHaveProperty('c');
expectTypeOf(obj).toHaveProperty('a').toBeNumber();
expectTypeOf(obj).toHaveProperty('b').toBeString();
expectTypeOf(obj).toHaveProperty('a').not.toBeString();