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.
Code
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 deskHow 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `normalizePhone` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.