typescript:Mapped Types

type Person = {
  name: string;
  age: number;
  location: string
}

// 1、Mapped Types 只匹配泛型的key,自定义value类型
type OptionFlag<T> = {
  [Property in keyof T]: boolean
}
const t1:OptionFlag<Person> = {
  name: false,
  age: false,
  location: false
}

// 2、Mapping Modifiers 匹配修饰符
type PersonReadonly = {
  readonly name: string;
  readonly age: number;
  readonly location?: string
}

// remove readonly: location非必填
type OptionFlagRemoveReadonly<T> = {
   -readonly [Property in keyof T] : T[Property]
}
const optionFlagRemoveReadonly: OptionFlagRemoveReadonly<PersonReadonly> = {
  name: "name",
  age: 11,
}

// remove options:location必填
type OptionFlagRemoveReadonly2<T> = {
   -readonly [Property in keyof T]-?: T[Property]
}
const optionFlagRemoveReadonly2: OptionFlagRemoveReadonly2<PersonReadonly> = {
  name: "name",
  age: 11,
  location: 'uuu'
}




// 3、Key Remapping via as 重新匹配key
// Capitalize 大写
type Getter<T> = {
  [Property in keyof T as `get${Capitalize<string & Property>}`]: T[Property]
}

const tt:Getter<Person> = {
  getName: "11",
  getAge: 11,
  getLocation: "11"
}

// Remove the 'kind' property
type RemovePersonName<T>= {
  [Property in keyof T as Exclude<Property, 'name'>] : T[Property]
}

const removePersonName:RemovePersonName<Person> = {
  age: 11,
  location: 'ss'
}


// function
type EventConfig<Events extends { kind: string }> = {
    [E in Events as E["kind"]]: (event: E) => void;
}

type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };

type Config = EventConfig<SquareEvent | CircleEvent>


type EventConfig2<Events extends {kind: string}> = {
    [E in Events as E['kind']] : (event:E)=> void
}

const a:EventConfig2<SquareEvent | CircleEvent> = {
    square: ({kind, x, y})=>{
        console.log("square", {kind, x, y})
    },
    circle: ({kind, radius})=>{
        console.log("circle", {kind, radius})
    }
}

a.square({kind: "square", x: 0, y: 9})
a.circle({kind: "circle", radius: 9})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值