简体   繁体   English

打字稿:如何声明具有从 IIFE 返回的自定义属性的函数的类型

[英]Typescript: How to declare the type for a function with custom properties that is returned from an IIFE

Say I have an object like this说我有一个这样的对象

const someObject: SomeObject = {
  someMethod: (function() {
    function mainMethod(x) {return x+1}
    yolo.subMethod = function(x) { return x-1 }

    return mainMethod;
  })()
}

I tried defining its type like this:我尝试像这样定义它的类型:

type SomeObject = {
  someMethod: {
    (x:number): number
    subMethod(x:number): number
  }
}

however I am getting Parameter 'x' implicitly has an 'any' type.但是我得到Parameter 'x' implicitly has an 'any' type. warnings in everything inside the IIFE, which means my type is not applied. IIFE 中所有内容中的警告,这意味着我的类型未应用。

I have already read this similar answer however it doesn't seem to work.我已经阅读了这个类似的答案,但它似乎不起作用。

I am quite new to TS, and I am not yet familiar with more intricate usecases such as this, so any help would be much appreciated.我对 TS 很陌生,我还不熟悉诸如此类的更复杂的用例,因此非常感谢任何帮助。

Contextual typing (where TS infers parameter types based on expected type) has its limitations.上下文类型(其中 TS 根据预期类型推断参数类型)有其局限性。 One of them is that the function has to be assigned directly to a typed reference.其中之一是必须将函数直接分配给类型化引用。 Since mainMethod is not directly assigned anywhere upon declaration it will not benefit form contextual typing.由于mainMethod在声明时未在任何地方直接分配,因此不会从上下文类型中受益。 It will be checked in the return , but it will not be contextually typed.它将在return检查,但不会根据上下文键入。

You will have to declare the parameter types explicitly to the functions.您必须向函数显式声明参数类型。 If you want to keep things dry you could define the type in relation to the inferred constant type instead:如果你想让事情保持干燥,你可以定义与推断的常量类型相关的类型:

const someObject = {
    someMethod: (function () {
        function mainMethod(x: number) { return x + 1 }
        mainMethod.subMethod = function (x: number) { return x - 1 }

        return mainMethod;
    })()
}

type SomeObject = typeof someObject

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM