Dev Helpers
← Back

Parse a numeric input strictly

Parse a numeric input strictly using TypeScript.

Open this example in the interactive library

Source code

type Fields = { name: string; age: number; subscribed: boolean };
const initial: Fields = { name: "Ada", age: 30, subscribed: false };
console.log(
  ((s: string): number | null => (/^\d+$/.test(s) ? Number(s) : null))("30px"),
);

Sample output

null