【问题标题】:Is there a way to "extend an interface while creating an object" in typescript?有没有办法在打字稿中“在创建对象时扩展接口”?
【发布时间】:2021-11-05 06:48:40
【问题描述】:

假设有一个接口限制了对象中可以使用的键或值类型。 例如,这样的接口可以用于存储一些计算。

interface CheckNumberMethods {
    [key: string]: (n: number) => boolean
}

因此,在使用某些方法创建实际对象时,我会应用该接口让 IDE 检查类型不匹配。

const myMethods:CheckNumberMethods = {
    greaterThanFive: (n: number) => n > 5,
    isEven: (n: number) => n % 2 === 0,
}

但是现在对象被MyMethodsType 类型卡住了。虽然我希望该类型代表我创建的实际对象。在此示例中,对象的类型应如下所示:

{
   greaterThanFive: (n: number) => boolean;
   isEven: (n: number) => boolean;
}

当然,这是自然行为,但是有没有办法在创建对象时进行类型检查,但保留原始对象的类型以供“外部”使用?

在这个例子中,简单地扩展接口并将扩展的接口应用到对象上就可以了,但是在更大的规模或更复杂的类型上就很麻烦了。

【问题讨论】:

    标签: typescript types interface


    【解决方案1】:

    为了推断出确切的属性并使对象可分配给CheckNumberMethods 接口,您应该创建一个具有适当约束的函数。 示例:

    interface CheckNumberMethods {
      [key: string]: (n: number) => boolean
    }
    
    const myMethods = {
      greaterThanFive: (n: number) => n > 5,
      isEven: (n: number) => n % 2 === 0,
    }
    
    const handle = <Obj extends CheckNumberMethods>(obj: Obj) => obj
    
    // {
    //     greaterThanFive: (n: number) => boolean;
    //     isEven: (n: number) => boolean;
    // }
    const result = handle(myMethods)
    

    Playground

    我从myMethods 中删除了显式类型CheckNumberMethods,因为它会影响handle 函数的返回类型。

    因此,您只能通过额外的功能推断出确切的属性。

    【讨论】:

    • 用 js 函数修复类型问题似乎很奇怪,但效果很好,谢谢!
    • 一旦你明确地将CheckNumberMethods 类型应用于myMethods,TS 就不再能够推断出确切的属性。将其视为阴影
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多