在 TypeScript 中基于接口创建对象
要基于接口创建对象,请将对象的类型声明为接口,例如 const obj1: Employee = {}。 该对象必须符合接口中的属性名称和值的类型,否则类型检查器会抛出错误。
interface Employee {
salary: number;
name: string;
address: {
country: string;
city: string;
};
}
// ✅ Declare directly
const obj1: Employee = {
salary: 100,
name: 'James',
address: {
country: 'Chile',
city: 'Santiago',
},
};
// ✅ Using type assertion
const obj2 = {} as Employee;
obj2.name = 'Carl';
obj2.salary = 200;
代码片段中的第一个示例直接将对象声明为 Employee 类型。
如果我们事先没有所有属性,则可以使用默认值:
interface Employee {
salary: number;
name: string;
address: {
country: string;
city: string;
};
}
// ✅ Declare directly
const obj1: Employee = {
salary: 0,
name: '',
address: {
country: '',
city: '',
},
};
但是,我们不能省略在接口上定义的任何必需属性。
第二个示例使用类型断言将对象的类型设置为接口中指定的类型。
interface Employee {
salary: number;
name: string;
address: {
country: string;
city: string;
};
}
const obj2 = {} as Employee; // 👈️ type assertion
obj2.name = 'Carl';
obj2.salary = 200;
当我们有关于 TypeScript 不知道的值类型的信息时,使用类型断言。
在上面的示例中,我们告诉 TypeScript obj2 变量将是 Employee 类型,因此它不必担心。
这是因为当我们使用 as Employee 语法时,我们告诉 TypeScript obj2 变量已经拥有一个 Employee 拥有的所有属性。
如果要将接口中的属性标记为可选,可以使用问号。
interface Employee {
salary?: number; // 👈️ optional
name?: string; // 👈️ optional
address: {
country: string;
city: string;
};
}
const obj1: Employee = {
address: {
country: 'Chile',
city: 'Santiago',
},
};
当一个属性被标记为可选时,我们不需要在初始化特定类型的对象时设置它。
可选属性可以是指定类型或未定义。
基于接口创建对象的另一种方法是定义初始化函数。
interface Employee {
salary: number;
name: string;
address: {
country: string;
city: string;
};
}
function createEmployee(options?: Partial<Employee>): Employee {
const defaults = {
salary: 0,
name: '',
address: {
country: '',
city: '',
},
};
return {
...defaults,
...options,
};
}
const obj2: Employee = createEmployee({ name: 'Alice' });
// 👇️ {salary: 0, name: 'Alice', address: {country: '', city: ''}}
console.log(obj2);
createEmployee 函数可以使用选项对象或根本不使用参数来调用。
我们使用 Partial 实用程序类型将 Employee 接口中的所有属性设置为函数参数中的可选属性。
函数传递的任何值都将覆盖默认值。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。