Functions Flashcards
What is a function type expression?
A function type expression is the simplest way to describe a function. These types are syntactically similar to arrow functions.
The syntax (a: string) => void
means “a function with one parameter, named a
, of type string
, that doesn’t have a return value”. Just like with function declarations, if a parameter type isn’t specified, it’s implicitly any
.
Source typescriptlang
What are call signatures?
In JavaScript, functions can have properties in addition to being callable. However, the function type expression syntax doesn’t allow for declaring properties. If we want to describe something callable with properties, we can write a call signature in an object type:
type DescribableFunction = { description: string; (someArg: number): boolean; }; function doSomething(fn: DescribableFunction) { console.log(fn.description + " returned " + fn(6)); }
Note that the syntax is slightly different compared to a function type expression - use :
between the parameter list and the return type rather than =>
.
Source typescriptlang
What are construct signatures?
JavaScript functions can also be invoked with the new
operator. TypeScript refers to these as constructors because they usually create a new object. You can write a construct signature by adding the new keyword in front of a call signature:
type SomeConstructor = { new (s: string): SomeObject; }; function fn(ctor: SomeConstructor) { return new ctor("hello"); }
Some objects, like JavaScript’s Date object, can be called with or without new. You can combine call and construct signatures in the same type arbitrarily:
interface CallOrConstruct { new (s: string): Date; (n?: number): number; }
Source typescriptlang
What are generic functions?
In TypeScript, generics are used when we want to describe a correspondence between two values. We do this by declaring a type parameter in the function signature:
function firstElement<Type>(arr: Type[]): Type | undefined { return arr[0]; }
TypeScript will always try to infer the generic types for their usage in functions. For example:
function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] { return arr.map(func); } // Parameter 'n' is of type 'string' // 'parsed' is of type 'number[]' const parsed = map(["1", "2", "3"], (n) => parseInt(n));
Source typescriptlang
How can you constrain the generic types of a functions?
With extends
.
Sometimes we want to relate two values, but can only operate on a certain subset of values. In this case, we can use a constraint to limit the kinds of types that a type parameter can accept.
Fore example:
function longest<Type extends { length: number }>(a: Type, b: Type) { if (a.length >= b.length) { return a; } else { return b; } } // longerArray is of type 'number[]' const longerArray = longest([1, 2], [1, 2, 3]); // longerString is of type 'alice' | 'bob' const longerString = longest("alice", "bob"); // Error! Numbers don't have a 'length' property const notOK = longest(10, 100);
Source typescriptlang
Common errors when constraining generics.
Returning the constrain object instead of the infered type.
Example:
function minimumLength<Type extends { length: number }>( obj: Type, minimum: number ): Type { if (obj.length >= minimum) { return obj; } else { return { length: minimum }; // Error Type '{ length: number; }' is not assignable to type 'Type'. } }
It might look like this function is OK - Type is constrained to { length: number }
, and the function either returns Type or a value matching that constraint. The problem is that the function promises to return the same kind of object as was passed in, not just some object matching the constraint.
Source typescriptlang
How can you manually specify the generic type in a function
Adding the Type
between <>
before the argument list when calling the generic functions.
function combine<Type>(arr1: Type[], arr2: Type[]): Type[] { return arr1.concat(arr2); } const arr = combine<string | number>([1, 2, 3], ["hello"]);
Source typescriptlang
When should you specify the generic type in a generic function?
Whenever Typescript can’t infer the type properly.
For Example:
function combine<Type>(arr1: Type[], arr2: Type[]): Type[] { return arr1.concat(arr2); }
Normally it would be an error to call this function with mismatched arrays:
const arr = combine([1, 2, 3], ["hello"]); // Error Type 'string' is not assignable to type 'number'.
If you intended to do this, however, you could manually specify Type:
const arr = combine<string | number>([1, 2, 3], ["hello"]);
Source typescriptlang
How can you add optional parameters to a function type expression?
Marking the parameter as optional with ?
:
function f(x?: number) { // ... } f(); // OK f(10); // OK
How can you provide a parameter default to a function?
What are function overloads and how can you create them in TypeScript?
In TypeScript, we can specify a function that can be called in different ways by writing overload signatures. To do this, write some number of function signatures (usually two or more), followed by the body of the function:
function makeDate(timestamp: number): Date; function makeDate(m: number, d: number, y: number): Date; function makeDate(mOrTimestamp: number, d?: number, y?: number): Date { if (d !== undefined && y !== undefined) { return new Date(y, mOrTimestamp, d); } else { return new Date(mOrTimestamp); } } const d1 = makeDate(12345678); const d2 = makeDate(5, 5, 5); const d3 = makeDate(1, 3); // Error: No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.
In this example, we wrote two overloads: one accepting one argument, and another accepting three arguments. These first two signatures are called the overload signatures.
Then, we wrote a function implementation with a compatible signature. Functions have an implementation signature, but this signature can’t be called directly. Even though we wrote a function with two optional parameters after the required one, it can’t be called with two parameters!
Source typescriptlang
What is the problem with this code:
function fn(x: string): void; function fn() { // ... } fn();
The signature of the implementation is not visible from the outside. When writing an overloaded function, you should always have two or more signatures above the implementation of the function.
The implementation signature must also be compatible with the overload signatures.
Source typescriptlang
What is the problem with this code:
function len(s: string): number; function len(arr: any[]): number; function len(x: any) { return x.length; }
This function is fine; we can invoke it with strings or arrays. However, we can’t invoke it with a value that might be a string or an array, because TypeScript can only resolve a function call to a single overload:
len(""); // OK len([0]); // OK len(Math.random() > 0.5 ? "hello" : [0]); // ERROR: No overload matches this call . . .
Because both overloads have the same argument count and same return type, we can instead write a non-overloaded version of the function:
function len(x: any[] | string) { return x.length; }
Always prefer parameters with union types instead of overloads when possible
Source typescriptlang
Explain control flow infered this
TypeScript will infer what the this
should be in a function via code flow analysis, for example in the following:
const user = { id: 123, admin: false, becomeAdmin: function () { this.admin = true; }, };
TypeScript understands that the function user.becomeAdmin
has a corresponding this
which is the outer object user
.
TypeScript Handbook. “Functions: Declaring this in a Function.” Retrieved 2023-03-22.
How can you declare this
in a function?
The JavaScript specification states that you cannot have a parameter called this
, and so TypeScript uses that syntax space to let you declare the type for this in the function body.
interface DB { filterUsers(filter: (this: User) => boolean): User[]; } const db = getDB(); const admins = db.filterUsers(function (this: User) { return this.admin; });
This pattern is common with callback-style APIs, where another object typically controls when your function is called. Note that you need to use function and not arrow functions to get this behavior:
interface DB { filterUsers(filter: (this: User) => boolean): User[]; } const db = getDB(); const admins = db.filterUsers(() => this.admin); // Error: The containing arrow function captures the global value of 'this'. Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
TypeScript Handbook. “Functions: Declaring this in a Function.” Retrieved 2023-03-22.