function length(value: string | null): number { return value === null ? 0 : value.length; }
function fallback(value: number | null | undefined): number { return value ?? 100; }
interface Profile { name: string; address?: { city: string }; }
const profile: Profile = { name: "蓝色天空网" };
console.log(length("hello"), length(null));
console.log(fallback(0), fallback(null), fallback(undefined));
console.log(profile.name, profile.address?.city, profile.address?.city ?? "未知城市");
本例需在 固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行
入口文件:examples/72409463321fb4692dc3b5c1/core/core.ts
预期结果与验证条件观察提示
- 长度5、0
- 默认值0、100、100
- 蓝色天空网、undefined、未知城市;undefined必须作为明确结果展示而非空白
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联72章) · 含当前章节或实例 · mbskycom202611a325.zip