面试题答案
一键面试// 定义userInfo的类型
type UserInfo = {
name: string;
age: number;
address: {
city: string;
country: string;
};
hobbies: string[];
// 预留可能新增的phone字段类型,这里假设为string类型
phone?: string;
};
// 通过解构赋值获取name、age和address.city
function getUserInfo(userInfo: UserInfo) {
const { name, age, address: { city } } = userInfo;
return { name, age, city };
}
// 示例用法
const user: UserInfo = {
name: '张三',
age: 30,
address: {
city: '北京',
country: '中国'
},
hobbies: ['阅读', '运动'],
phone: '12345678901'
};
const result = getUserInfo(user);
console.log(result);
当对象结构发生变化(新增phone
字段)时,通过定义UserInfo
类型,在函数参数和对象字面量赋值时,TypeScript 会进行类型检查。如果新增字段后函数调用处没有正确传入新字段,编译阶段就会报错,从而优化代码健壮性和简洁性。