ts key键映射用as

172 阅读1分钟

as

在ts4.1或者以上, 您可以在映射类型中重新映射键使用映射类型中的 as 子句

type MappedTypeWithNewProperties<Type> = {
    [Properties in keyof Type as NewKeyType]: Type[Properties]
}

你可以利用模板文字类型这一特性, 从以前的属性名中创建新的属性名。

给属性重新起名字

type Getters<Type> = {
    [Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
}

interface Person {
    name: string;
    age: number;
    location: string
}

type LazyPerson = Getters<Person>

等于

type LazyPerson = {
    getName: () => string;
    getAge: () => number;
    getLocation: () => string;
}

注意: 这里值得注意的是Capitalize这个方法(给字符串的首字母大写)

Capitalize

Capitalize

把字符串的首字母转为大写。

```
type LowercaseGreeting = "hello , world";
type Greeting = Capitalize<LowercaseGreeting>;

type Greeting = "Hello, world"
```