typescript keyof
时间: 2023-05-11 09:03:07 浏览: 64
TypeScript 中的 keyof 关键字用于获取一个类型的所有属性名,返回一个字符串字面量类型。例如,如果有一个类型 Person,包含 name 和 age 两个属性,那么 keyof Person 的结果就是 "name" | "age"。
相关问题
as keyof typeof
`as keyof typeof` is a TypeScript type assertion syntax that allows you to cast a value to a specific key of a type. It is often used to access a specific property of an object without hardcoding the property name as a string.
For example, consider the following code:
```typescript
const obj = {
foo: 'hello',
bar: 'world'
};
const key = 'foo';
const value = obj[key];
```
In this code, we have an object `obj` with two properties `foo` and `bar`. We want to access the value of the property whose name is stored in the variable `key`. However, TypeScript will give us an error because `key` is a string and not a valid key of `obj`.
To fix this, we can use `as keyof typeof`:
```typescript
const obj = {
foo: 'hello',
bar: 'world'
};
const key = 'foo' as keyof typeof obj;
const value = obj[key];
```
Now, TypeScript knows that `key` is a valid key of `obj` and we can safely access the value of the property.
Note that `typeof` is used here to get the type of `obj`. This allows us to avoid hardcoding the type of `obj` and makes the code more reusable.
keyof typeof
keyof typeof用于获取一个对象类型的所有属性名的联合类型。typeof操作符用于获取一个值的类型,而keyof操作符用于获取一个类型的所有属性名。因此,keyof typeof可以用于获取一个对象的所有属性名的联合类型。
举个例子,假设我们有一个对象person,其类型为Person:
```
type Person = {
name: string;
age: number;
gender: string;
};
const person: Person = {
name: "John",
age: 30,
gender: "male"
};
```
我们可以使用keyof typeof来获取person对象的所有属性名的联合类型:
```
type PersonKeys = keyof typeof person;
// PersonKeys的类型为 'name' | 'age' | 'gender'
```
这样,我们就可以使用PersonKeys来限制一个函数的参数类型,以确保只能传入person对象的属性名作为参数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [typescript类型判断](https://blog.csdn.net/meng16/article/details/111404848)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [TypeScript中的keyof、typeof、索引访问类型、条件类型](https://blog.csdn.net/jieyucx/article/details/131363515)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]