【问题标题】:Passing object (interface) without writing keys不写key传递对象(接口)
【发布时间】:2022-11-21 09:08:59
【问题描述】:

简单来说,我有一个接口A:

interface A { names: string[]; nr: number; }

我可以传递/创建一个 A 对象,这样:

{ names: ['John'], nr: 11 }

但是,如果不编写密钥我怎么能通过它,如下所示:

{ ['John'], 11 }

打字稿有可能吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    好像您正在寻找元组类型:

    type A = [name: string[], nr: number];
    
    const example: A = [['John'], 11];
    

    这是一个示例TS playground link

    编辑:键控数组在 TS/JS 中并不是真正的东西,但也许你可以使用一个函数来获得想要的结果?

    interface A { names: string[]; nr: number; }
    
    function makeA (names: A["names"], nr: A["nr"]): A {
        return { names, nr };
    }
    
    const a: A = makeA(['John'], 11);
    
    console.log(a.name, a.nr);
    

    这是TS playground link

    【讨论】:

    • 它工作正常,但我不能像 object.nr 等那样使用它。我仍然希望有这种可能性。
    • 我更新了一个工厂函数模式,它可能更接近您想要的行为。
    猜你喜欢
    • 2011-10-26
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多