as keyof typeof
时间: 2023-10-16 09:10:04 浏览: 50
`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.