NonNullable Strips Null And undefined

NonNullable removes null and undefined from a union, turning optional draft fields into present values once a normalization step has filled them.

TypescriptForm Validation

Code

typescriptsnippet
19 lines
type Draft = {
  phone: string | null;
  note?: string | undefined;
};

// NonNullable 把 null 与 undefined 从联合里剔除
type PresentPhone = NonNullable<Draft['phone']>;

function normalizePhone(value: string | null): PresentPhone {
  return (value ?? '').replace(/[^+0-9]/g, '');
}

console.log(JSON.stringify(normalizePhone('+86 138 0000 0000')));
console.log(JSON.stringify(normalizePhone(null)));

// note?: string | undefined 里的 undefined 同样被剔除
type Note = NonNullable<Draft['note']>;
const note: Note = 'left at front desk';
console.log(note);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

"+8613800000000"
""
left at front desk

How the snippet works

NonNullable Strips Null And undefined keeps everything in the function normalizePhone.

Using it

The primary signature is function normalizePhone(value: string | null)

Key statements

return (value ?? '').replace(/[^+0-9]/g, '');

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `normalizePhone` at load time.