TypeScript theorytheory 0/50 · 0%
Web3 integration · medium

36. Web3 typing patterns: bigint & addresses

Modelling on-chain values precisely with the type system.

On-chain amounts (wei, token units) commonly exceed `Number.MAX_SAFE_INTEGER`, so they're represented with the native `bigint` type, written with an `n` suffix.

ts
const oneEther: bigint = 1_000_000_000_000_000_000n;
const gasPrice: bigint = 30_000_000_000n;
const totalCost: bigint = oneEther + gasPrice; // bigint + bigint only

type Address = `0x${string}`;

function isAddress(value: string): value is Address {
  return /^0x[0-9a-fA-F]{40}$/.test(value);
}

`bigint` cannot be mixed with `number` in arithmetic (`1n + 1` is a type error), which prevents silent precision loss. The template literal type `` `0x${string}` `` documents that an address string must start with `0x`, giving lightweight compile-time hinting beyond a plain `string`, even though full validation still needs a runtime check like `isAddress`.

Check your understanding

  1. 1. Why use `bigint` for wei amounts instead of `number`?

  2. 2. Can you write `1n + 1` in TypeScript?

  3. 3. What does the template literal type `` `0x${string}` `` accomplish?