TypeScript
Functions
WebDevLee
2023. 5. 25. 18:53
타입스크립트의 Functions에 대해 작성하였습니다.
< Introduction >
When we declare a function in JavaScript, we often expect it to be invoked with arguments of a certain type. JavaScript does not share our expectations: its type flexibility often allows functions to be invoked with unexpected argument types.
Example)
function printLengthOfText(text) {
console.log(text.length);
}
printLengthOfText(3); // Prints: undefined
< Parameter Type Annotations >
To fix above problem, In TypeScript, function parameters can be given type annotations with the same syntax as variable declarations - a colon next to the name
Parameters that we do not provide type annotations for are assumed to be of type any - the same way variables are.
Example)
// annotation example
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
greet('Katz'); // Prints: Hello, Katz
greet(1337); // Error: argument '1337' is not assignable to parameter of type 'string'
// any example
function printKeyValue(key: string, value) {
console.log(`${key}: ${value}`);
}
printKeyValue('Courage', 1337); // Prints: Courage: 1337
printKeyValue('Mood', 'scared'); // Prints: Mood: scared
< Optional Parameters >
TypeScript normally gives an error if we don't provide a value for all arguments in a function.
To indicate that a parameter is intentionally optional, we add a ? after its name.
Example)
// problem
function greet(name: string) {
console.log(`Hello, ${name || 'Anonymous'}!`);
}
greet('Anders'); // Prints: Hello, Anders!
greet(); // TypeScript Error: Expected 1 arguments, but got 0.
// solution
function greet(name?: string) {
console.log(`Hello, ${name|| 'Anonymous'}!`);
}
greet(); // Prints: Hello, Anonymous!
< Default Parameters >
If a parameter is assigned a default value, TypeScript will infer the variable type to be the same as the default value's type.
Example)
function greet(name = 'Anonymous') {
console.log(`Hello, ${name}!`);
}
< Inferring Return Types >
TypeScript can also infer the types of values returned by functions.
It does this by looking at the types of the values after a function's return statements.
Example)
// good
function createGreeting(name: string) {
return `Hello, ${name}!`;
}
const myGreeting = createGreeting('Aisle Nevertell');
// bad
function ouncesToCups(ounces: number) {
return `${ounces} cups`;
}
const liquidAmount: number = ouncesToCups(3);
// Type 'string' is not assignable to type 'number'.
< Explicit Return Types >
To explicit what type a function returns, we can add an explicit type annotation after its closing parenthesis.
Example)
// function keyword
function createGreeting(name?: string): string {
if (name) {
return `Hello, ${name}!`;
}
return undefined;
//Typescript Error: Type 'undefined' is not assignable to type 'string'.
};
// arrow function
const createArrowGreeting = (name?: string): string => {
if (name) {
return `Hello, ${name}!`;
}
return undefined;
// Typescript Error: Type 'undefined' is not assignable to type 'string'.
};
< Void Return Types >
It is often preferred to use type annotations for functions, even when those functions don't return anything.
When there isn't returned value, must treat the return type as void.
Example)
function logGreeting(name: string): void {
console.log(`Hello, ${name}!`)
}
< Documenting Functions >
It's common in TypeScript to see a third comment style: documentation comments.
- first line : /**
- final line : */
- each line : *
Example)
/**
* Returns the sum of two numbers.
*
* @param x - The first input number
* @param y - The second input number
* @returns The sum of `x` and `y`
*
*/
function getSum(x: number, y: number): number {
return x + y;
}