Skip to content

Function Statements - interface assignment, errorless property assignmentΒ #46941

Closed
@brandon942

Description

@brandon942

Suggestion

πŸ” Search Terms

Function Statement , static variables

⭐ Suggestion

Problem case:

function func(a, b) {
	func.counter = 1 // Property 'counter' does not exist on type '(a: any, b: any) => void'.  ts(2339)
}

My 3 suggestions related to this problem.

  1. Allow access/assignment of properties on a function object inside of the function body
  2. A way to attach a type/interface/typehint onto a function in a function statement (Type Cast or Assertions on the FunctionDeclarationΒ #40378)
  3. Inference of arguments and the return type of a function

πŸ“ƒ Motivating Example

πŸ’» Use Cases

If you need static variables in func then using the func object as a bag is the only good solution in javascript.
I am not sure if this typescript error is a bug or a feature since assigning properties to func in the outer scope does not cause errors

function func(a, b) {}
func.counter = 1 // ok

I found the best way to get rid of the error is to add // @ts-ignore in front of the property assignment. However doing this everywhere just to deal with a typescript shortcoming isn't ideal.

My failed attempts to work around this error by working with typescript:

// trying an interface
// One shouldn't create an outside interface for properties that are only ever used inside of func
interface anObject {  (...args:any):any;   [x:string]:any  }

// Currently there is no syntax for assigning a type or interface onto func
// function func(a, b) {  func.counter = 1  } // Hence Suggestion 2.

// One has to break the function statement and turn it into an expression
// Typescript should not force one to change the structure of existing code to accommodate it. it should be simply additive.
var func : anObject = function (a, b) {  func.counter = 1  } // ok

// But now the info on arguments and return type of func is lost  (...args:any)=>any
// Attempt to fix this:
// fails
var func: (typeof func) & {counter:number} = function func__(params) {  func.counter = 1  } // 'func' is referenced directly or indirectly in its own type annotation.  ts(2502)
// fails
var func: { <T extends (...args: any) => any>(...args:Parameters<T>):ReturnType<T>; counter:number}  = function (a, b) {  func.counter = 1  }
// fails
var func: {(a, b):void; counter:number} = function (a, b) {  func.counter = 1  } // Property 'counter' is missing ...  ts(2741)
// Hence suggestion 3.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions