TypeScript in React
types
- TypeScript is a superset of JavaScript that adds types.
- Type Inferences:TypeScript is that when we declare a variable with an initial value, the variable can never be reassigned a value of a different data type.
tsc
;run the xx.ts- Type Shapes:TypeScript’s tsc command will let you know if your code tries to access properties and methods that don’t exist:
- 如果值没有被定义,那么后续可以被定义成任何类型的值
- Variable Type Annotations:
let mustBeAString : string; mustBeAString = 'Catdog';
functions
- Parameter Type Annotations
- we add a ? after its name. This tells TypeScript that the parameter is allowed to be undefined and doesn’t always have to be provided.
- Default Parameters:TypeScript infers the type of an initialized variable to be the same as the type of its initial value
- Inferring Return Types:
- Explicit Return Types;
- Void Return Type:
complex types
- array:Keeping track of the array’s type means keeping track of every element’s type.
- Array Type Annotations:
let names: string [] = ['Danny', 'Samantha'];
- Multi-dimensional Arrays:
string [][]
: A two-dimensional array of strings. Each element of bestMealPlan is itself an array of strings. number [][][]
: A three-dimensional array of numbers. Each element is a two-dimensional array of numbers (number [][]).- Tuples:
let tup: [string, string] = ['hi', 'bye'];
- Tuples have a predefined number of elements.
- Each tuple instance must always have exactly the number of elements defined in its type.
- Array Type Inference:
- Rest Parameters:I don’t know how many arguments I’ll get, but collect all of them into a single array."
<The ...numbers rest parameter collects all the arguments into an array called numbers>
- Spread Syntax:
- string [][][] (a three-dimensional array of strings):It’s an array where each element is a two-dimensional array
- string [][] (a two-dimensional array of strings):each element is itself a string array
custom types
- Enums:Enums in TypeScript are best used when you need to represent a fixed set of related constants with meaningful names, and you want to enforce type safety
enum Day {
Monday = 1,
Tuesday,
Wednesday
}
console.log (Day.Monday); // Output: 1
console.log (Day [1]); // Output: 'Monday'
- String Enums vs. Numeric Enums:number enums, TypeScript generates reverse mapping. You can get the name of a member using its numeric value.
- String enums do not support reverse mapping. You cannot retrieve a member name using its value.
- Object Types:
- Type Aliases:type
<alias name>
=<type>
- Function Types: function can be assigned to variable。
type StringsToNumberFunction = (arg0: string, arg1: string) => number;
- Generic Types:
type typeName<T>
T within the type annotation as a type placeholdertype Family<T> = { parents: [T, T], mate: T, children: T [] };
- 这个是一种对于类型规范化的设置,t 可以换成任何的数据类型或者其他定义好的数据类型。
- Generic Functions:
function getFilledArray<T>(value: T, n: number): T [] {
return Array (n).fill (value);
}
- annotate the property types using colons to separate each property from its data type enclosed within curly braces
Union Types
- When we combine types, it is called a union
- Defining Unions:
let ID: string | number;
string | number is a union that allows ID to be a string or a number - Type Narrowing:a process where the compiler refines the type of a variable within a specific block of code, based on certain conditions or checks.
- Inferred Union Return Types:TypeScript will look at the contents of a function and infer which types the function can return. If there are multiple possible return types, TypeScript will infer the return type as a union.
- Unions and Arrays:
const timesList: (string | number)[] = [dateNumber, dateString];
- Common Key Value Pairs:Any properties or methods that are not shared by all of the union’s members won’t be allowed and will produce a TypeScript error.
- Unions with Literal Types:
Type Narrowing
- Type guards:
- Using in with Type Guards:typeof operator is used to check the primitive type of a variable. It works with basic types such as string, number, boolean, symbol, undefined, and bigint/The in operator is used to check if a property exists in an object. It works specifically for objects or object types
- In JavaScript and TypeScript, an object is a collection of key-value pairs. Each key (or property) is associated with a value, and that value can be of any type (e.g., a string, number, array, function, or even another object).
- Void as a return type: It is used to signify that a function does not return anything./
- type AliasName = SomeType;
- Narrowing with else:
- Narrowing After a Type Guard: 在只有两种数据类型进行选择的情况下,如果没有 if-else 语句 也是可以直接用 if + 两个 return 完成语句的执行
- What is type narrowing?: Type narrowing is when TypeScript can infer more specific types based on the variable’s surrounding code.
- when do we need quote,and when dont
- need quote:
- dont need quote:
- Interfaces and Types:interface can only be used to type objects, while type can be used to type objects, primitives, and more
- Interfaces and Classes: apply a type to an object/class with the implements keyword
- difference between class and object
- object:object as a real-world entity that has certain attributes (properties) and behaviors (methods).
- class:as a blueprint for creating objects. When you create an object from a class, you call that object an instance of the class.
- Deep Types:
- Composed Types:
- Extending Interfaces:
- Index Signatures:dynamic keys
- Optional Type Members:We can denote any type member as optional using the ? operator after the property name and before the colon (:)