实现说明
函数 normalizePhone定义了示例的全部动作。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件在加载时定义 normalizePhone。
主要签名是 function normalizePhone(value: string | null)
核心语句
return (value ?? '').replace(/[^+0-9]/g, '');
代码示例
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);