gpt4 book ai didi

javascript - 通用函数类型不适用于返回的对象成员

转载 作者:行者123 更新时间:2023-11-30 19:25:43 24 4
gpt4 key购买 nike

我正在定义一个函数,它返回一个对象,该对象的成员是具有相同有效负载的函数。有效负载类型通过 generic 定义,它扩展了对象。但是,流提示泛型类型与传递的类型不同:

export const getObj = <T: {}>(url: string) => ({
create: (entity: T) => console.log(url, entity),
...
});

const url = '/some-path';

type TEntity = {
some: string,
};

const entity: TEntity = {
some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

流提示:

^ Cannot call instance.create with entity bound to entity because TEntity 2 is incompatible with T 2.

Try .

我做错了什么?

最佳答案

如有疑问,be more explicit.

// @flow

type EntityFactory<T> = $ReadOnly<{|
create: (T) => void,
|}>;

export const getObj = <T>(url: string): EntityFactory<T> => ({
create: (entity: T) => console.log(url, entity),
});

const url = '/some-path';

type TEntity = {
some: string,
};

const entity: TEntity = {
some: 'value',
};

const instance = getObj<TEntity>(url);

instance.create(entity);

关于javascript - 通用函数类型不适用于返回的对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com