Typescript Type Level Custom Error Message For Utility Types

Acid Coder
3 min readJun 28, 2023

Part 1: Typescript Type Level Custom Error Message, Move Runtime Error to Compile time Error!

In the previous article, we have learned how to create custom type level error message for our function

In this article, We are going to learn how to create custom type level error message for…the type itself!

Now imagine we want to create a type converter that convert true and false to 1 and 2 respectively

We want to convert either true or false, but we don’t want to convert both

type A <T extends true | false, U = T> = T extends true ? 1 : 2

type X = A<boolean> // no error, but we dont want this
// ^?
type Y = A<true>
// ^?
type Z = A<false>
// ^?
const x1:X = 1
const x2:X = 2
const y:Y = 1
const z:Z = 2

playground

No error or what so ever

Normally the solution is:

type A <T extends true|false, U = T> = boolean extends T ? "You cannot convert type `boolean` !": T extends true ? 1 : 2
type X = A<boolean> // no error, but we dont want this
// ^?
type Y = A<true>
// ^?
type Z = A<false>
// ^?
const x1:X = 1 // error
const x2:X = 2 // error
const y:Y = 1
const z:Z = 2

playground

nice, we have the error, the user know what is wrong!

but we can do better, we can let the user know something is wrong earlier

type A <T extends [U] extends [boolean] ? (boolean extends U ? "error: cannot use `boolean`, please use `true` or `false` instead" : U) : "error: expected a boolean", U = T> = T extends true ? 1 : 2

type X = A<boolean> // error with custom error message!
// ^?
type Y = A<true>
// ^?
type Z = A<false>
// ^?
const x1:X = 1 // no error, because error is lifted
const x2:X = 2 // no error, because error is lifted
const y:Y = 1
const z:Z = 2

playground

If you are creating utility type library, this will further enhance your users dev experience

  1. It warns your users when they use your type improperly
  2. The error acts as quick documentation that teaches your users how to use the type correctly

--

--

Acid Coder

Typescript Zombie. Youtube Pikachu On Acid. (Unrelated to programming but by watching it you become a good developer overnight)