TypeScript 中的{[key: string]: string} 是什么意思
{[key: string]: string}
语法是 TypeScript 中的索引签名,当我们事先不知道类型属性的所有名称但知道值的形状时使用。 索引签名指定字符串类型的键和值。
// 👇️ function returning index signature
// (a key-value structure with key and value strings)
function getObj(): { [key: string]: string } {
return { name: 'Tom', country: 'Chile' };
}
// 👇️ Interface using index signature
interface Person {
[index: string]: string;
}
// 👇️ const p1: Person
const p1: Person = { name: 'Tom', country: 'Chile' };
// 👇️ Type using index signature
type Animal = {
[index: string]: string;
};
const a1: Animal = { name: 'Alfred', type: 'dog' };
{[key: string]: string}
语法是 TypeScript 中的索引签名,当我们事先不知道类型属性的所有名称但知道值的形状时使用。
示例中的索引签名意味着当用字符串索引对象时,它将返回一个字符串。
我们可能还会在示例中看到索引签名 {[key: string]: any}
。 它代表一个键值结构,当用字符串索引时返回任何类型的值(非常广泛)。
让我们看一个示例,说明如果我们尝试添加与索引签名中指定类型不同的值,TypeScript 会如何警告我们。
interface Person {
[index: string]: string;
}
// ⛔️ ERROR: Type 'number' is not assignable to type 'string'.
const p1: Person = { name: 'Tom', age: 30 };
我们已经指定当具有 Person
类型的对象被字符串索引时,它应该返回一个字符串。
尝试设置一个值为数字的字符串的键会给我们带来错误。
我们可能会尝试使用索引签名覆盖特定属性的类型。
interface Person {
[index: string]: string;
// ⛔️ Error: Property 'age' of type 'number' is not
// assignable to 'string' index type 'string'.
age: number;
}
但是示例中 age
属性的类型与字符串索引的类型不匹配,所以 TypeScript 给了我们一个错误。
在这种情况下,我们可以将字符串索引的类型设置为联合。
interface Person {
[index: string]: string | number;
age: number;
name: string;
}
// 👇️ const p1: Person
const p1: Person = { name: 'Tom', country: 'Chile', age: 30 };
具有字符串类型索引签名的值的类型是字符串和数字的联合。
age
和name
属性的值是联合的子类型,因此我们不会收到错误。
尝试向不在联合中的类型添加属性会导致错误。
interface Person {
[index: string]: string | number;
age: number;
name: string;
// ⛔️ ERROR: Property 'colors' of type 'string[]' is not assignable
// to 'string' index type 'string | number'.ts(2411)
colors: string[];
}
如果我们需要防止分配给它们的索引,还可以将索引签名设置为readonly
。
interface ReadonlyObj {
readonly [index: string]: string;
}
const obj: ReadonlyObj = {
name: 'Tom',
country: 'Chile',
};
// ⛔️ Index signature in type 'ReadonlyObj'
// only permits reading.
obj.name = 'Alfred';
我们将字符串索引的类型设置为readonly
,因此如果我们尝试写入具有字符串键的属性,类型检查器会给我们一个错误。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。