We’re just learning a little bit before we get to functions
-
1. Type narrowing
What is type narrowing?
English plays a role of Type Narrowingtypeof 'erke' === 'string'
To change the path of our code execution, and during the execution of our code we can execute to a smaller type than we declared and this process is called shrinking
We achieve type Guards by narrowing down types.
Common types of protection are as follows
-
typeof
-
= = =,! = =
-
instanceof
-
in
-
Object.prototype.toString.call(add)
-
The typeof typeof is reduced
Checking the value of a type in Typescript makes typeof a type protection based on the value of the typeof operation
type nameType = number | string
function getName(name: nameType) :void {
if (typeof name === 'string') {
console.log(name.toUpperCase());
} else {
console.log(name.toFixed(2));
}
}
getName('erkelost') // ERKLOST
getName(123456) / / 123456.00
Copy the code
-
Switch equal shrink type shrink
type styleType = "padding" | "margin" | "width" | "height"
function getStyle(style: styleType) {
switch (style) {
case 'padding':
console.log(`${style}=100px`);
break;
case 'margin':
console.log(`${style}=100px`);
break;
case 'width':
console.log(`${style}=100px`);
break;
case 'height':
console.log(`${style}=100px`);
break;
}
}
getStyle('padding') // padding = 100px
Copy the code
-
instanceof
type mathType = number | Date
function math(num: mathType) {
if (num instanceof Date) {
console.log(new Date());
} else {
console.log(num);
}
}
math(new Date())
math(132456)
Copy the code
-
in
The in operator determines whether an object has a named property. The in operator returns true if the specified property is in the specified object or stereotype chain
type Fish = {
swimming: () = > void
}
type Dog = {
running: () = > void
}
function walk(animal: Fish | Dog) {
if ('swimming' in animal) {
animal.swimming()
} else {
animal.running()
}
}
const fish: Fish = {
swimming() {
console.log("swimming")
}
}
walk(fish) // swimming
export{}
Copy the code
function
Functions are an important part of JavaScript development, and functions can serve as first-class citizens (either as arguments or as return values).
1. When a function is used as an argument
function name() {
console.log('adny');
}
type getType = () = > void // By default, a function type is defined that returns no value
function get(fn: getType) {
fn()
}
get(name)
export{}
Copy the code
If a function returns a number, it returns a number. If it does not return a number, it returns a void
type constFnType = (n1: number, n2: number) = > number
const addNum: constFnType = (a1: number, a2:number) = > {
return a1 + a2
}
console.log(addNum(20.50)); / / 70
Copy the code
3. Optional types of arguments (the optional types of y are number and undefined union)
function foo(x: number, y? : number) :number {
console.log(x + y);
return x + y
}
foo(20.30)
foo(20)
Copy the code
4. Default parameters
function adny(y: number, x: number = 10) :number {
console.log(x, y)
return x + y
}
adny(30)
Copy the code
this
Normally, TypeScript assumes that the function sayName has an external object info corresponding to this, so it uses this as that object
const info = {
name: 'adny'.sayName:function() {
console.log(this);
console.log(this.name); // adny
}
}
info.sayName()
Copy the code
But if we were to write this function out then we would have an error because we can’t get the value of this, we’re not sure what this is and it’s unsafe for Typescript code to compile and we would have an error, right
function sayName() {
console.log(this.name); // An outer value of 'this' is shadowed by this container.
}
const info = {
name: 'adny',
sayName
}
info.sayName()
Copy the code
So we need to specify the type of this and again, TypeScript does type checking to make our code safer
type thisType = { // Define an object type
name: string
}
function sayName(this: thisType) { // We define this to specify that we can find this object
console.log(this.name);
}
const info = {
name: 'adny',
sayName
}
info.sayName()
Copy the code
Function overloading
In typescript, if we write an add function to add variables that may have different types, we can set it
function addS(num1: number | string, num2: number | string) :number | string {
return num1 + num2
}
Copy the code
This is because the operator “+” cannot be applied to type “string | number” and “string | number”.
In typescript, we can write different overload signatures to indicate that functions can be called in different ways; Generally, write two or more overloaded signatures, and then write a generic function and implementation
Function overloading is defined as function overloading: several functions with the same name but different arguments are function overloading
When we call a function we pass arguments to determine which execution function we want to call based on the arguments we pass in
function addS(num1: number, num2:number) :number
function addS(num1: string, num2:string) :string
function addS(num1: any, num2: any) :any {
console.log(num1 + num2);
return num1 + num2
}
addS('ERKELOST'.'adny') / /ERKELOSTadny
addS(20.30) / / 50Copy the code
Join types and overloads
Define a function that we need to pass in a string and an array to get the length of the array or the string
We can use the union type
type lengthType = string | any[]
function getLength(len: lengthType) :number {
console.log(len.length);
return len.length
}
getLength([1.2.3]) / / 3
getLength('hhjjk') / / 5
Copy the code
overloading
function getlength(len: string) :number
function getlength(len: any[]) :number
function getlength(len: any) {
return len.length
}
Copy the code