Home > Software engineering >  How to set the signature type of a function statement in Typescript?
How to set the signature type of a function statement in Typescript?

Time:10-01

I have a function signature type like this:

type MyFunc = (foo: string) => string

How can I use this signature to set the type of a function statement (not function expression)? For example when I have an array of functions like

[(foo) => foo   "bar", () => "bar"]

Without setting a type for the array, can I somehow enforce the signature of the functions inside the array so that () => "bar" throws an error because of a type mismatch? I imagine something like this:

[((foo) => foo   "bar"): MyFunc, (() => "bar"): MyFunc]

Obviously this is not valid syntax. Is there a way to achieve this?

CodePudding user response:

You can use as, but () => string is currently a valid subtype of (foo: string) => string, so you will not get an error. (The implementation is free to ignore any arguments.)

type MyFunc = (foo: string) => string

[
    ((foo) => foo   "bar") as MyFunc, // No error
    (() => "bar") as MyFunc,          // No error
    ((x: number) => "bar") as MyFunc, // Error
]
  • Related