TypeScriptBasic types
Function types
Typing parameters, the return value, and functions themselves as values.
Example
#TypeScript
function formatPrice(amount: number, currency = 'USD', discount?: number): string {
const final = discount ? amount * (1 - discount) : amount
return `${final.toFixed(2)} ${currency}`
}
console.log(formatPrice(49))
console.log(formatPrice(100, 'USD', 0.2))Result
49.00 USD 80.00 USD
Definition and usage
#In a function, you type the parameters and, optionally, the return value: function add(a: number, b: number): number. With strict turned on, a parameter with no type causes an error, because it would implicitly get the type any.
You mark optional parameters with a question mark (title?: string), and you give default values just like in JavaScript (limit = 10). The compiler also checks the number of arguments at the call site.
An arrow type describes a function as a value: (value: string) => boolean. A type like that comes in handy for callbacks, event handlers, and passing functions into components.
Syntax
#Syntax
function name(param: type, optional?: type): returnType { … }
type Fn = (param: type) => returnTypeMore examples
#TypeScript
type Validator = (value: string) => boolean
const isEmail: Validator = (value) => value.includes('@')
const notEmpty: Validator = (value) => value.trim().length > 0
function validate(value: string, rules: Validator[]): boolean {
return rules.every((rule) => rule(value))
}
console.log(validate('emma@codeworlds.com', [notEmpty, isEmail]))
console.log(validate(' ', [notEmpty, isEmail]))Result
true false
Good practices
#- It’s worth writing the return type explicitly on exported functions. It guards against accidentally changing the contract.
- Put optional parameters at the end of the list.
Related entries
#- voidThe return type of functions that return nothing.
- Type inferenceThe compiler figuring out types automatically, without you writing annotations.
- Generics <T>Types and functions with a type parameter that work for many types without losing precision.
- TuplesFixed-length arrays where each position has its own type.
- Function overloadsSeveral signatures for one function: the result type depends on which arguments you call it with.
Spotted a mistake or missing an example? Write to us.