Home > Back-end >  Applying a function type to an object's arrow function member in Typescript?
Applying a function type to an object's arrow function member in Typescript?

Time:09-10

Given the following object:

const parameters = {
  someNumberMember: 1 as number,
  someArrowFunctionMember: () => { return true; }
}

Is there a way to directly assign a type definition to someArrowFunctionMember? I mean a "complete" type definition of the function, not defining the parameter and return types. So something like this:

...
  someArrowFunctionMember: () => { return true; } as DesiredType,
...                                               ^^^^^^^^^^^^^^^ doesn't work

Context: I know there's 2 better ways to do this.

  1. Assign a type to parameters that defines someArrowFunctionMember's type like this:
type ParametersType = {
  someNumberMember: number;
  someArrowFunctionMember: () => boolean;
}

const parameters: ParametersType = {
  someNumberMember: 1 as number,
  someArrowFunctionMember: () => { return true },
}
  1. Extract the arrow function into a variable like this:
const handler: () => boolean = () => { return true };

const parameters = {
  someNumberMember: 1 as number,
  someArrowFunctionMember: handler,
}

I'm just curious if there is a syntax that allows me to do this directly.

I tried using the as keyword because it works when using a classic function:

const parameters = {
  someNumberMember: 1 as number,
  someArrowFunctionMember: function() {return true;} as () => boolean,
}                                                    ^^^^^^^^^^^^^^^^^ works like a charm

I also tried using type casting with the pointy brackets because it also works on classic functions:

const parameters = {
  someNumberMember: <number> 1,
  someArrowFunctionMember: <Function> function() {return true;},
}

Note: This initially didn't work until I realized the problem wasn't Typescript itself but rather using TS in conjunction with JSX, which makes sense. After disabling jsx in tsconfig, it works (at least in TS playground).

I found this answer but it doesn't seem to work anymore or there's something in my tsconfig preventing it from working.

CodePudding user response:

Have you tried placing the whole function within brackets:

...
  someArrowFunctionMember: (() => { return true; }) as DesiredType,
... 

Note:

Typescript will infer the type implicitly so usually you dot need a cast.

  • Related