首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >怎样才能让typescript类型系统知道返回值的类型?

怎样才能让typescript类型系统知道返回值的类型?
EN

Stack Overflow用户
提问于 2020-12-17 16:43:57
回答 1查看 24关注 0票数 0

我刚开始使用typescript,我正在尝试将so代码从js迁移到ts,同时阅读ts HandBook。

下面是每个级别的开发人员和用户之间的关系:

lib developer -> ProductProvider ->产品开发人员-> Product ->产品用户-> robot

这看起来很顺利,除了我不知道如何告诉typescript机器人的类型,这是汇编函数返回值的类型,也是Product函数返回值的类型。

代码语言:javascript
复制
interface Injection {
    [index: string]: string
}

interface Component {
    id: string,
    install: (injection: Injection) => void
}

interface InitOptions {
    id: string,
    screenType: string,
    SoC: string,
    components: Component[],
}

type Assembler = (injection: object, options: object) => unknown;

type ProductProvider = (initOptions: InitOptions, assembler: Assembler) => (options: object) => ReturnType<typeof assembler>

function ProductProvider(initOptions: InitOptions, assembler: Assembler): (options: object) => ReturnType<typeof assembler> {
    //some work to init
    const installedInjection: Injection = {};
    initOptions.components.forEach((component => component.install(installedInjection)));
    
    return function Product(startOption: object): ReturnType<typeof assembler> {
        return assembler(installedInjection, startOption);
    }
}

export default ProductProvider;

const assembler: Assembler = (injection: object, options: object) => ({ injection, options });

const Product = ProductProvider({
    id: 'XMC9E8DCO5EXEU',
    screenType: 'LCD',
    SoC: 'RX-78',
    components: [{
        id: 'component1',
        install(injection) {
            //some work
            const content = 'whatever';
            injection[this.id] = content;
        } 
    }]
 }, assembler);

const robot = Product({ battery: 'A' });

Assembler类型中,因为ProductProvider的用户可以自由地进行汇编,所以我认为该函数的类型将返回unknown。

但实际上,产品开发人员知道传递给ProductProvider的汇编参数返回一个值,并且它的类型是object。

而其他产品开发人员也可能返回另一个接口或类型。

怎样才能让typescript类型系统知道返回值的类型?然后我们就可以享受智能感知了。

XD

EN

回答 1

Stack Overflow用户

发布于 2020-12-25 16:10:00

代码语言:javascript
复制
type Assembler<T> = (injection: object, options: object) => T;

type ProductProvider<T> = (initOptions: InitOptions, assembler: Assembler<T>) => (options: object) => T;

好了。

enter image description here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65337267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档