From d2cdadc856bfd60814f85d22a9fcdde56be7896d Mon Sep 17 00:00:00 2001 From: tactonbishop Date: Sun, 3 Jul 2022 20:00:05 +0100 Subject: [PATCH] Last Sync: 2022-07-03 20:00:05 --- Programming_Languages/TypeScript/Functions.md | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/Programming_Languages/TypeScript/Functions.md b/Programming_Languages/TypeScript/Functions.md index 6e38b0d..e8f1b6a 100644 --- a/Programming_Languages/TypeScript/Functions.md +++ b/Programming_Languages/TypeScript/Functions.md @@ -4,31 +4,32 @@ tags: - typescript --- +# Functions + ## Basic typing within a function: arguments and return values With functions we can apply types to the return value, the parameters and any values that are included within the function body. -````tsx +```ts function search(query: string, tags: string[]): string {} -```` +``` We can also specify optional parameters with use of the `?` symbol: -````tsx -function search(query: string, **tags?: string[]**): string {} -```` +```ts +function search(query: string, tags?: string[]): string {} +``` ### Utilising custom types ---- Whilst we can use standard JS types with the parameters and return value, the real benefit comes when you use custom types. For instance we can specify that an object passed to a function must match the shape of a custom type or interface. Similarly we can ensure that for functions that return objects, the object that is returned must satisfy the shape of the custom object. -````tsx +```ts async function getContributorData( contributorName: string ): Promise {} -```` +``` For example, this function has a return signature which indicates that it will return a promise matching a type of shape `IContributor` @@ -38,15 +39,15 @@ For example, this function has a return signature which indicates that it will r As well as typing the values that a function receives and returns, you can type the function itself. **This is most useful when you are using higher-order functions and passing functions as parameters to another function.** In these scenarios you will want to type the function that is being passed as a parameter. There are several ways to do this. We'll use the following basic function as our demonstration: -````tsx +```ts function hoFunc(integer: number, addFunction: any): number { return addFunction(integer); } -```` +``` ### Use `typeof` -````tsx +```ts // Declare an adding function const addTwo = (int: number) => int + 2; @@ -58,6 +59,6 @@ hoFunc(3, addTwo); function hoFunc(integer: number, addFunction: typeof addTwo): number { return addFunction(integer); } -```` +``` This way we just use the native `typeof` keyword to assert that any call of `hoFunc` should pass a function of the type `addTwo`