I know I have asked this before, and I cannot find the question nor remember the answer.
I have an object with several methods with the same signature:
{
foo: function(){
return []; // (return Array<T>)
},
bar: function(){
return []; // (return Array<T>)
},
baz: function(){
return []; // (return Array<T>)
}
}
When I declare the interface for this object:
interface SomeObj {
foo: Function,
bar: Function,
baz: Function
}
but I want to declare a type for these functions, something like this:
type TestSuiteGetterFn <T>() => Array<T>;
interface SomeObj {
foo: TestSuiteGetterFn,
bar: TestSuiteGetterFn,
baz: TestSuiteGetterFn
}
but this does not compile.
I have rarely found something so difficult to Google as this one.
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
You simply forgot the equals sign when declaring your function type.
TypeScript Playground Permalink
type TestSuiteGetterFn<T> = () => Array<T>;
interface SomeObj {
foo: TestSuiteGetterFn<string>,
bar: TestSuiteGetterFn<number>,
baz: TestSuiteGetterFn<string>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With