Skip to Content
ExplanationsType Inference

Type Inference

This page explores some nuanced aspects of TypeScript’s type inference.

Type Widening

In mutable context a literal type is inferred  as its base type:

import { } from "tstyche"; const = { : 2, : [3, 3] }; ()..<{ : number; : number[] }>();

To tell to the type checker that a type should not be widened, use type assertions :

import { } from "tstyche"; const = { : 6 as , : [9, 9] as 9[] }; ()..<{ : 6; : 9[] }>();

It is also possible to use the const type assertion to convert the entire object, but in this case a different type is created:

import { } from "tstyche"; const = { : 6, : [9, 9] } as ; ()..<{ readonly : 6; readonly : readonly [9, 9] }>();

Excess Property Checks

If passed as arguments, the object literals undergo the excess property checks :

import { } from "tstyche"; let : { ?: number } = {}; = { silent: true, : 800 };
Object literal may only specify known properties, and 'silent' does not exist in type '{ timeout?: number | undefined; }'.
// Same as above, object literal may only specify known properties ({ : true, : 800 })...<{ ?: number }>(); <{ ?: number }>()...({ : true, : 800 }); // But object types are allowed to have excess properties <{ : true; : 800 }>()..<{ ?: number }>(); <{ ?: number }>()..<{ : true; : 800 }>();

Generally these failures prevent outdated assertions hanging around in your tests.

If the excess property checks is not what you need, follow the above link to learn how to get around them. For example, pass a reference instead of an object literal:

import { } from "tstyche"; const = { : true, : 800 }; ()..<{ ?: number }>();
Last updated on