在 TypeScript 中定义和使用键值对
使用索引签名在 TypeScript 中定义键值对,例如 const employee: { [key: string]: string | number } = {}。 当我们事先不知道类型键的所有名称,但我们知道它们值的形状时,使用索引签名。
const employee: { [key: string]: string | number } = {};
employee.name = 'James';
employee.salary = 100;
// ?️ {name: 'James', salary: 100}
console.log(employee);
我们使用索引签名来定义 TypeScript 中的键值对;。
{[key: string]: string} 语法是 TypeScript 中的索引签名,当我们事先不知道类型属性的所有名称但知道值的形状时使用。
我们可能还会在示例中看到索引签名 {[key: string]: any} 。 它代表一个键值结构,当用字符串索引时返回任何类型的值(非常广泛)。
const employee: { [key: string]: any } = {};
employee.name = 'James';
employee.salary = 100;
employee.years = [2021, 2022];
// ?️ {name: 'James', salary: 100, years: [2021, 2022]}
console.log(employee);
{[key: string]: any} 索引签名用于在我们事先不知道类型键的名称和值的形状时创建键值对。
我们可以声明提前知道的键和值的类型,并为不知道的键和值使用 any 类型。
type Employee = {
[key: string]: any;
name: string;
salary: number;
};
const employee: Employee = {
name: 'James',
salary: 100,
};
employee.country = 'Chile';
employee.years = [2021, 2022];
我们声明了 name 和 salary 属性的类型,我们提前知道这些属性,并使用索引签名仍然允许我们为对象分配任何键和任何值。
如果我们尝试将不兼容类型的属性分配给该对象,则会出现错误。
type Employee = {
[key: string]: string;
};
const employee: Employee = {
name: 'James',
};
// ⛔️ Type 'number' is not assignable
// to type 'string'.ts(2322)
employee.salary = 100;
我们使用了带有字符串键和值的索引签名,因此如果我们尝试向对象添加数字值,类型检查器会显示错误。
索引签名 {[key: string]: string} 意味着当使用字符串键索引对象时,该值始终是字符串。
type Employee = {
[key: string]: string;
// ⛔️ Error: Property 'salary' of type 'number'
// is not assignable to 'string' index type 'string'.
salary: number;
};
要解决这个问题,我们必须使用 union 类型。
type Employee = {
[key: string]: string | number;
salary: number;
};
const employee: Employee = {
name: 'James',
salary: 100,
};
新的索引签名意味着如果对象使用字符串键进行索引,它会返回一个字符串或数字值,因此我们可以在具有数字值的类型上设置其他属性。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。