简体   繁体   English

在打字稿中映射对象类型

[英]Map an objects type in typescript

I am looking for a way of a "mapped" object type in typescript.我正在寻找一种在打字稿中“映射”对象类型的方法。

I have a the following typings:我有以下类型:

interface Factory<T>{
     serialize: (val: T)=>void,
     deserialize: ()=>T,
}
interface MyDict{
     [key: string]: Factory<any>
}

function deserialize(dict: MyDict){
     let mapped = {};
     for(let k in dict){
          mapped[k] = dict[k].deserialize();
     }
     return mapped;
}

What I want is that the return type of map is correctly determined.我想要的是正确确定地图的返回类型。

So when doing this:所以当这样做时:

let mapped = map({
    foo: {deserialize: ()=>'hello world'}, 
    foo2: {deserialize: ()=>123}, 
    foo3: {deserialize: ()=>({foo4: 'foo4'})}
});

mapped should be typed as {foo: string, foo2: number, foo3: {foo4: string}} .映射应键入为{foo: string, foo2: number, foo3: {foo4: string}}

You can do this using a mapped type.您可以使用映射类型执行此操作。 The function will also need to be generic in order to capture the actual type of the argument:该函数还需要是泛型的,以便捕获参数的实际类型:

interface Factory<T>{
     serialize?: (val: T)=>void,
     deserialize: ()=>T,
}
interface MyDict{
     [key: string]: Factory<any>
}

type FactoryReturnType<T extends MyDict> = {
    [K in keyof T]: ReturnType<T[K]['deserialize']>
}

function deserialize<T extends MyDict>(dict: T){
     let mapped = {} as FactoryReturnType<T>;;
     for(let k in dict){
          mapped[k] = dict[k].deserialize();
     }
     return mapped;
}

let mapped = deserialize({
    foo: {deserialize: ()=>'hello world'}, 
    foo2: {deserialize: ()=>123}, 
    foo3: {deserialize: ()=>({foo4: 'foo4'})}
});

mapped.foo3.foo4

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM