是否可以将同级属性的类型分配给嵌套对象中的另一个属性?

问题描述 投票:0回答:1

我想创建函数,让我们称之为

test
,它将在第一级采用带有动态键的嵌套对象,并自动为您提供方法类型,因此我不必手动键入它,但它仍然采用泛型类型传递的其他方法和属性,下面的示例进行解释。

type NestedProperties = {
property: () => any,
  anotherProperty: () => any,
  method: (data: ReturnType<Test['property']>) => any,
}

使用示例:


function test<T extends Record<string, NestedProperties>>(obj: T){}

test({
  list: {
    property: () => 'string',
    anotherProperty: () => 1, -- will not result as () => any.
    method: (data -- and this will automatically infer type of returntype of list.property) {
       ...do something
    }
  }
});
typescript
1个回答
0
投票

您可以使用 TypeScript 的实用类型,例如 ReturnType 和条件类型。以下是如何定义测试函数,以根据属性的返回类型自动推断方法属性中数据参数的类型:

type NestedProperties<T> = {
    property: () => T;
    anotherProperty: () => any;
    method: (data: ReturnType<NestedProperties<T>['property']>) => any;
};

function test<T extends Record<string, NestedProperties<any>>>(obj: T) {}

// Example usage
test({
    list: {
        property: () => 'string',
        anotherProperty: () => undefined,
        method: (data) => {
            // data will be inferred as 'string'
            // Do something with data
        },
    },
});

希望对您有帮助,祝您好运! :)

© www.soinside.com 2019 - 2024. All rights reserved.