Skip to content

Narrowing Type ​

āļ„āļ·āļ­āļāļēāļĢāļ•āļąāļ” case āļ„āļ§āļēāļĄāđ€āļ›āđ‡āļ™āđ„āļ›āđ„āļ”āđ‰āļ‚āļ­āļ‡ Type āļ—āļĩāđˆāđ€āļāļīāļ”āļ‚āļķāđ‰āļ™ āđ€āļžāļ·āđˆāļ­āđƒāļŦāđ‰āđ€āļĢāļēāļˆāļąāļ”āļāļēāļĢāļāļąāļš āļŠāļ™āļīāļ”āļ‚āļ­āļ‡ Object āđ„āļ”āđ‰āļ–āļđāļāļ•āđ‰āļ­āļ‡āļ™āļąāđ‰āļ™āđ€āļ­āļ‡

āļāļēāļĢ narrow type āļ‚āļ­āļ‡ unknown ​

ts
/**
 * A custom type guard function that determines whether
 * `value` is an array that only contains numbers.
 */``
function isNumberArray(value: unknown): value is number[] {
  return (
    Array.isArray(value) && value.every(element => typeof element === "number")
  );
}

const unknownValue: unknown = [15, 23, 8, 4, 42, 16];

if (isNumberArray(unknownValue)) {
  // Within this branch, `unknownValue` has type `number[]`,
  // so we can spread the numbers as arguments to `Math.max`
  const max = Math.max(...unknownValue);
  console.log(max);
}

Ref:

āļ—āļĩāļ™āļĩāđ‰āļĄāļēāļĨāļ­āļ‡ Narrow āđ€āļžāļ·āđˆāļ­āđ€āļŠāđ‡āļ„ Record Type āļāļąāļ™ āđ‚āļ”āļĒāđƒāļŠāđ‰ lib data validation āļ—āļĩāđˆāļŠāļ·āđˆāļ­ zod

ts
import { z } from 'zod';

function isRecord(object: unknown): object is Record<string, unknown> {
  const recordSchema = z.record(z.unknown());
  return recordSchema.safeParse(object).success;
}

function findLength(object: unknown): number {
  if (Array.isArray(object)) {
    return console.log(object.length);
  } else if (isRecord(object)) {
    return Object.keys(object).length;
  }
  throw new Error(`Input object doesn't support type`);
}