TS Learning Notes (Arrays, Objects, interfaces)
TS array
- Array deconstruction, array expansion operator, array traversal.
let x: number; let y: number; let z: number;
let five_array = [0.1.2.3.4];
[x,y,z] = five_array;
console.log([x,y,z])/ / 0
// Array expansion operator
let four_array = [0.1.2.3];
let five_array = [...four_array, 4];
// go through the number group
let number: string[] = ["1"."2"."3"];
for (let i of number) {
console.log(i);
}
Copy the code
Summary: The array and JS operations in TS do not change much.
TS object
- Object deconstruction, object expansion operator.
let person = {
name: "coolFish".
sex: "Male".
};
let { name, sex } = person;
/ / extension
let person = {
name: "coolFish".
sex: "Male".
address: "Xiamen".
};
// Assemble objects
letpersonWithAge = { ... person, age:24 };
Copy the code
Summary: not much different from JS.
TS interface
- Object shape.
interface Person {
name: string;
age: number;
}
let semlinker: Person = {
name: "coolFish".
age: 24.
};
Copy the code
Summary; I’m going to define an object that has a name and an age, so when I create this object, I’m going to give it a name and an age.
- Optional | read-only.
//readonly Indicates read-only, which can be changed only during creation
interface Person {
readonly name: string;
age? :number;
}
//ReadonlyArray
Remove all mutable methods to ensure that they do not change after creation
let a: number[] = [1.2.3.4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
Copy the code
- Arbitrary attributes: In addition to mandatory, optional, sometimes we need to accept uncertain attributes.
interface Person {
name: string;
age? :number;
[propSex: string] :any;
}
const newObject = { name: "kakuqo", sex: 'male' }
Copy the code
Summary: Reserve a socket to receive arbitrary attributes.
- The difference between interface and type aliases.
/ / interface
interface Point {
age: number;
sex: string;
}
interface SetPoint {
(age: number, sex: string) :void;
}
// Type alias
type Point = {
age: number;
sex: string;
};
type SetPoint = (age: number, sex: string) = > void;
Copy the code
Summary: It looks the same, but the declaration has changed.
- Other Types: Type aliases can be used for several Other Types, such as primitive Types, union Types, and tuples
// Primitive type
type age = number;
// Union type
type PartialPointX = { x: number; };
type PartialPointY = { y: string; };
type PartialPoint = PartialPointX | PartialPointY;
/ / yuan group
type Data = [number.string];
Copy the code
- Interface and type aliases are not mutually exclusive. Interfaces can Extend type aliases and vice versa.
// Interface extension type alias
type PartialPointX = { x: number; };
interface Point extends PartialPointX { y: number; }
Copy the code