当前位置:网站首页>Typescript keyboard mapping

Typescript keyboard mapping

2022-06-11 07:59:00 YY little monster

1. What is a mapping type ?
Create a new type from the old type , We call it mapping type
We can go through +/- To specify whether to add or remove Read only and optional modifiers

interface TestInterface1{
    
    name:string,
    age:number
}
interface TestInterface2{
    
    readonly name?:string,
    readonly age?:number
}
type ReadonlyTestInterface<T> = {
    
    // [P in keyof T] effect :  Traverse all of the specified types key,  Add to current object 
    // readonly [P in keyof T]: T[P]
    // readonly [P in keyof T]?: T[P]
    -readonly [P in keyof T]-?: T[P]
}
// take TestInterface2 Cancel read only and optional 
//type MyType ={
    
// name:string,
// age:number
//}
type MyType = ReadonlyTestInterface<TestInterface2>

2. Because it is common to generate read-only attributes and optional attributes , therefore TS The internal has provided us with a ready-made implementation

/* read-only  type MyType2 = { readonly name:string, readonly age:number } */
type MyType2 = Readonly<TestInterface1>


/* Optional  type MyType3 = { name?:string, age?:number } */
type MyType3 = Partial<TestInterface1>



/* Read only optional  MyType4 ={ readonly name?:string, readonly age?:number } */
type MyType4 = Partial<Readonly<TestInterface1>>

3.Pick Mapping type
Map parts of the original type to the new type

interface TestInterface {
    
    name:string,
    age:number
}
/*type MyType = { name:string, */
type MyType = Pick<TestInterface, 'name'>

4.Record Mapping type
He will map all attribute values of one type to another and create a new type

type Animal = 'person' | 'dog' | 'cat';
interface TestInterface {
    
    name:string;
    age:number;
}
type MyType = Record<Animal, TestInterface>
/*type MyType ={ person:TestInterface, dog:TestInterface, cat:TestInterface } */
let res:MyType = {
    
    person:{
    
        name:'zs',
        age:18
    },
    dog:{
    
        name:'wc',
        age:3
    },
    cat:{
    
        name:'mm',
        age:2
    }
}

原网站

版权声明
本文为[YY little monster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110754014066.html