Typescript: Function types [duplicate] - javascript

Why doesn't Typescript warn me that the function I am defining does not match the interface declaration, but it does warn me if I try to invoke the function.
interface IFormatter {
(data: string, toUpper : boolean): string;
};
//Compiler does not flag error here.
var upperCaseFormatter: IFormatter = function (data: string) {
return data.toUpperCase();
}
upperCaseFormatter("test"); //but does flag an error here.

The interface ensures that all callers of functions that implement the interface supply the required arguments - data and toUpper.
Because TypeScript understands that JavaScript doesn't mind if you pass arguments that aren't used, it cleverly allows this in implementations.
Why is this okay? Because it means you can substitute any implementation of the interface without affecting calling code.
Example: You can substitute either IFormatter implementation and the code works.
interface IFormatter {
(data: string, toUpper: boolean): string;
};
var upperCaseFormatter: IFormatter = function (data: string) {
return data.toUpperCase();
}
var variableCaseFormatter: IFormatter = function (data: string, toUpper: boolean) {
if (toUpper) {
return data.toUpperCase();
}
return data.toLowerCase();
}
// Switch between these at will
//var formatter = upperCaseFormatter;
var formatter = variableCaseFormatter;
formatter("test", true);
If TypeScript didn't do this, your upperCaseFormatter would have to have to have a parameter called toUpper that wasn't used anywhere in the function - which makes the code less readable.

Related

args unable to be passed into wrapped function

I have several modules (or bridges) that follow the same format as below:
export interface Bridge {
foo: (a: string, b: boolean, c: string) => number;
bar: (a: number, b: number, c: string, d: string) => string;
x: (a: string) => boolean;
y: () => null;
}
As a result, I need to create a layer than does some if-else processing to import the respective module. However, the functions within these modules will require a fallback mechanism that is made to be generic.
export type BridgeFunctions = keyof Bridge;
/* Called when a particular bridge throws an error */
export async function fallback(fnName: BridgeFunctions, ...args: any[]): Promise<any> {
const fallbackBridge = await import('./fallbackBridge');
const fn = fallbackBridge[fnName];
return fn(...args);
}
However, VSCode returns me this error:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
Tried using call and apply, which led to this error instead:
The 'this' context of type ... is not assignable to method's 'this' of type '(this: any[]) => Promise<any>'.
Based on my understanding, in vanilla Javascript, passing args straight into fn should work. How do I emulate the same in TypeScript?
EDIT:
The Bridge modules are used as follows:
function getBridge(): Bridge {
if (inIOS()) {
return await import('./ios');
}
// ...
return await import ('./web');
}
export function foo(a: string, b: boolean, c: string): number {
try {
const bridge = await getBridge();
return bridge.foo(a, b, c);
} catch (error: any) {
// ...
if (error.bridge.failed) {
return await fallback('foo', a, b, c);
}
}
}
This is how I would do it.
Basically, you want to make sure the user passes valid arguments to your function. To do this, you set the args to be the parameters of the passed in function.
export async function fallback<FN extends keyof Bridge>(fnName: FN, args: Parameters<Bridge[FN]>){
Then, to bypass the error, just type fn to any:
const fn = fallbackBridge[fnName] as any;
return fn(...args);
Using any here is fine since you already know the types are compatible.
The problem here is that your fallbackBridge functions require a certain number of parameters but you give them the type " any[] " that could have any length.
You could bypass this error with return fn(...(args as Parameters<typeof fn>));

Writing Interface with ALL optional parameters Typescript

Consider this:
interface TArguments {
width?: number,
height?: number
}
interface TSomeFunction {
someFunction ({width, height}: TArguments): void
}
const someObject: TSomeFunction = {
someFunction ({width, height}) {
// do something, no return
}
}
Both paremeters are optional, this means that I can call someFunction like that:
someObject.someFunction() // but it is not passing through
I'm geting an Error "Expected 1 arguments, but got 0".
Am I missing something ?
How do I write an Interface when all parameters are optional?
Your interface should not concern about default values or destructuring, as those are implementation details. Just declare the parameter as optional, as if it was a scalar:
interface TSomeFunction {
someFunction (size? : TArguments): void
}
The implementation can then define both:
const someObject: TSomeFunction = {
someFunction({ width, height } = {}) {
// do something, no return
}
}
Your error must be coming from a different place (or try restarting your IDE, that is a source of a lot of frustration :)). Your second approach looks correct:
const someFunction = ({width, height}: TArguments = {}) => { ... }
Here is a working TypeScript playground link
EDIT You need to also specify that the parameter itself, not only its keys, is optional:
interface TSomeFunction {
someFunction (arguments?: TArguments): void; // Notice the question mark after the parameter expression
}
// Now you can either add a default value to your function
const someObject: TSomeFunction = {
someFunction ({width, height}: TArguments = {}) {}
}
// Or leave it optional without specifying a default value
const someObject: TSomeFunction = {
someFunction ({width, height}?: TArguments) {} // Notice the question mark
}

TypeScript: annotate ES5 generic class

I have the following code, in a file named storage.ts. Its purpose is to serve as a storage device for multiple parts of my API.
interface ICache<T> {
[key: string]: T
}
declare class Cacher<T> {
constructor (initialCache: ICache<T>)
define (key: string, val: T): void
get (key: string): T
remove (key: string): void
clear (): void
load (cacheObj: ICache<T>): void
}
function Cacher<T> (this: any, initialCache: ICache<T>) {
var cache: ICache<T> = initialCache
this.define = function (key: string, val: T) {
cache[key] = val
}
this.get = function (key: string) {
if (cache[key]) {
return cache[key]
} else {
throw new Error ("Key '" + key + "' doesn't exist")
}
}
this.remove = function (key: string) {
delete cache[key]
}
this.clear = function () {
cache = {}
}
this.load = function (cacheObj: ICache<T>) {
cache = cacheObj
}
}
export default Cacher
Usage example (containers.ts):
import Cacher from './storage'
type TemplateFunction = (options: object, config: object) => string
var Templates = new Cacher<TemplateFunction>({})
Everything is all fine and great, VSCode and TSLint don't throw any errors, etc., until I try and build with TypeDoc. Then, containers.ts gives this error:
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
and storage.ts gives this error twice, on line 6 and 15:
Duplicate identifier 'Cacher'
I might think this was just an issue with TypeDoc, but changing function Cacher<T> (this: any, initialCache: ICache<T>) { to export default function Cacher<T> (this: any, initialCache: ICache<T>) { and removing the last line gives this error:
Merged declaration 'Cacher' cannot include a default export declaration. Consider adding a separate 'export default Cacher' declaration instead.ts(2652)
I've spent hours trying to fix this. I've tried multiple different variations of this StackOverflow answer, but it doesn't allow for passing in a generic. Besides, I find let x = function() to be a lot less elegant than function x().
Random notes:
I replaced this: any with this: [an interface that represents this]. Same issue as before
For reasons I'd rather not go into, I do not want to convert it to a class
Possibly related to this error: https://github.com/microsoft/TypeScript/pull/3973
I'd love any help - sorry for the long post!

proper way to override function with different param types in TypeScript

TL;DR; my formatAPI function below is very much not the TYpeScript way of overriding a function...
I've got a function that might be called either of following four ways in JavaScript:
jsf.format("format", function(){ return ... }); // string, function
jsf.format("format"); // string
jsf.format({
"format1": function(){ return ... },
"format2": function(){ return ... }
}); // map[string:function]
jsf.format(); // no params
Each signature executes different logic beneath. CUrrently I've got the following:
function formatAPI(name: string, callback?: Function): any {
if (callback) {
registry.register(name, callback);
} else if (typeof name === 'object') {
registry.registerMany(name);
} else if (name) {
return registry.get(name);
} else {
return registry.list();
}
}
but it's inconsistent - e.g. second parameter is string. When I change it to string|Object than it fails on my logic (registry.register(name, callback); - name here has to be a string and string|Object is not assignable to string). I'm trying to find a clear and extensible solution (to be able to add more variations if I need to, in the future), I try to adapt another question but I fail.
I would appreciate help and/or advise on how should I declare all possible signatures for this function AND the function body.
It slices! it dices! It makes toast!
// Signatures
function formatAPI(): string[];
function formatAPI(name: string): string;
function formatAPI(name: string, callback: (arg: string) => void): void;
function formatAPI(map: { [name: string]: () => string }): void;
// Implementation
function formatAPI(nameOrMap?: string | { [name: string]: () => string }, callback?:(arg: string) => void): string | string[] | void {
if (typeof nameOrMap === 'string') {
if (callback) {
return registry.register(nameOrMap, callback);
} else {
return registry.get(nameOrMap);
}
} else if (...) {
// Keep adding checks here
}
}
One thing to note is that the compiler doesn't use the signatures to infer behavior for type guards. This means you should structure your code slightly more conservatively -- here, I put both string cases inside the typeof check.

How to define type for a function callback (as any function type, not universal any) used in a method parameter

Currently I have type definition as:
interface Param {
title: string;
callback: any;
}
I need something like:
interface Param {
title: string;
callback: function;
}
but the 2nd one is not being accepted.
The global type Function serves this purpose.
Additionally, if you intend to invoke this callback with 0 arguments and will ignore its return value, the type () => void matches all functions taking no arguments.
Typescript from v1.4 has the type keyword which declares a type alias (analogous to a typedef in C/C++). You can declare your callback type thus:
type CallbackFunction = () => void;
which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:
type CallbackFunctionVariadic = (...args: any[]) => void;
Then you can say, for example,
let callback: CallbackFunctionVariadic = function(...args: any[]) {
// do some stuff
};
If you want a function that takes an arbitrary number of arguments and returns anything (including void):
type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;
You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:
type CallbackFunctionSomeVariadic =
(arg1: string, arg2: number, ...args: any[]) => void;
This can be useful for things like EventEmitter handlers.
Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.
Following from Ryan's answer, I think that the interface you are looking for is defined as follows:
interface Param {
title: string;
callback: () => void;
}
You can define a function type in interface in various ways,
general way:
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
If you would like to use property syntax then,
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
If you declare the function type first then,
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
Using is very straight forward,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
You can declare a function type literal also , which mean a function can accept another function as it's parameter. parameterize function can be called as callback also.
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}
Here's an example of a function that accepts a callback
const sqk = (x: number, callback: ((_: number) => number)): number => {
// callback will receive a number and expected to return a number
return callback (x * x);
}
// here our callback will receive a number
sqk(5, function(x) {
console.log(x); // 25
return x; // we must return a number here
});
If you don't care about the return values of callbacks (most people don't know how to utilize them in any effective way), you can use void
const sqk = (x: number, callback: ((_: number) => void)): void => {
// callback will receive a number, we don't care what it returns
callback (x * x);
}
// here our callback will receive a number
sqk(5, function(x) {
console.log(x); // 25
// void
});
Note, the signature I used for the callback parameter ...
const sqk = (x: number, callback: ((_: number) => number)): number
I would say this is a TypeScript deficiency because we are expected to provide a name for the callback parameters. In this case I used _ because it's not usable inside the sqk function.
However, if you do this
// danger!! don't do this
const sqk = (x: number, callback: ((number) => number)): number
It's valid TypeScript, but it will interpreted as ...
// watch out! typescript will think it means ...
const sqk = (x: number, callback: ((number: any) => number)): number
Ie, TypeScript will think the parameter name is number and the implied type is any. This is obviously not what we intended, but alas, that is how TypeScript works.
So don't forget to provide the parameter names when typing your function parameters... stupid as it might seem.
There are four abstract function types, you can use them separately when you know your function will take an argument(s) or not, will return a data or not.
export declare type fEmptyVoid = () => void;
export declare type fEmptyReturn = () => any;
export declare type fArgVoid = (...args: any[]) => void;
export declare type fArgReturn = (...args: any[]) => any;
like this:
public isValid: fEmptyReturn = (): boolean => true;
public setStatus: fArgVoid = (status: boolean): void => this.status = status;
For use only one type as any function type we can combine all abstract types together, like this:
export declare type fFunction = fEmptyVoid | fEmptyReturn | fArgVoid | fArgReturn;
then use it like:
public isValid: fFunction = (): boolean => true;
public setStatus: fFunction = (status: boolean): void => this.status = status;
In the example above everything is correct. But the usage example in bellow is not correct from the point of view of most code editors.
// you can call this function with any type of function as argument
public callArgument(callback: fFunction) {
// but you will get editor error if call callback argument like this
callback();
}
Correct call for editors is like this:
public callArgument(callback: fFunction) {
// pay attention in this part, for fix editor(s) error
(callback as fFunction)();
}
There are various ways to define function types; however, some are better than others.
Although it is possible to use Function, the JavaScript function object, don't do that.
Source: TypeScript ESLint plugin recommended rule ban-types
Avoid the Function type, as it provides little safety for the following reasons:
It provides no type safety when calling the value, which means it's easy to provide the wrong arguments.
It accepts class declarations, which will fail when called, as they are called without the new keyword.
TypeScript supports multiple other ways. Most commonly, function type expressions are used. This method highly resembles arrow functions.
If arguments and return values are known to be of a certain form, then they should be typed.
For example,
interface Param {
callback: (foo: string, bar: number) => void
}
Note that these types can be as complex as needed, for example using object types or types created from other types.
If the types are truly unknown then prefer unknown over any.
Source: TypeScript ESLint plugin recommended rule no-explicit-any
When any is used, all compiler type checks around that value are ignored.
From the TS docs,
unknown is the type-safe counterpart of any.
Thus, using spread syntax,
interface Params {
callback: (...args: unknown[]) => unknown
}
Hopefully, this will help...
interface Param {
title: string;
callback: (error: Error, data: string) => void;
}
Or in a Function
let myfunction = (title: string, callback: (error: Error, data: string) => void): string => {
callback(new Error(`Error Message Here.`), "This is callback data.");
return title;
}
Typescript: How to define type for a function callback used in a method parameter?
You can declare the callback as 1) function property or 2) method:
interface ParamFnProp {
callback: (a: Animal) => void; // function property
}
interface ParamMethod {
callback(a: Animal): void; // method
}
There is an important typing difference since TS 2.6:
You get stronger ("sound") types in --strict or --strictFunctionTypes mode, when a function property is declared. Let's take an example:
const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { }
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works
// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...
Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array.
Summary
There is a type difference between function property and method declaration
Choose a function property for stronger types, if possible
Playground sample code
I've just started using Typescript and I've been trying to solve a similar problem like this; how to tell the Typescript that I'm passing a callback without an interface.
After browsing a few answers on Stack Overflow and GitHub issues, I finally found a solution that may help anyone with the same problem.
A function's type can be defined with (arg0: type0) => returnType and we can use this type definition in another function's parameter list.
function runCallback(callback: (sum: number) => void, a: number, b: number): void {
callback(a + b);
}
// Another way of writing the function would be:
// let logSum: (sum: number) => void = function(sum: number): void {
// console.log(sum);
// };
function logSum(sum: number): void {
console.log(`The sum is ${sum}.`);
}
runCallback(logSum, 2, 2);
In typescript 4.8, Function type gives error. Instead we can write the type explicitly as fn: () => void.
If you want to use args as well,
function debounce(fn: (...args: any[]) => void, ms = 300) {
If you are looking for input callback function like on change event then use the following
type Props = {
callBack: ChangeEventHandler<HTMLInputElement>;
}

Categories