目录
Basic typescript
What is typescript?
Configuring the TypeScript Compiler
Fundamental
build in types
TypeScript Simple Types
TypeScript Special Types
Type: unknown
Type: never
Type: undefined & null
Arrays
Tuple
Enums
functions
Object
Type Aliases
Interfaces
Union | (OR)
Optional Chaining
Basic typescript
学习视频来自:
https://www.youtube.com/watch?v=d56mG7DezGs
TypeScript Simple Types
What is typescript?
TypeScript is a syntactic superset of JavaScript which adds static typing.
This basically means that TypeScript adds syntax on top of JavaScript, allowing developers to add types
左边不可以给同一变量赋值不同的type。右边可以赋值不同的type,当它使用Math.round()的时候,不会报错啊!这就是弊端。typescript就加入了static typing。
Benefits:
- static typing
- code completion
- refactoring
- shorthand notations
How to compile?
tsc index.ts
Configuring the TypeScript Compiler
terminal:
tsc --init
Create tsconfig.json file
configure json:
create src directory
fix the path, uncomment the following thing
"rootDir": "./src",
"outDir": "./dist", /* Specify an output folder for all emitted files. */
"removeComments": true,
Fundamental
build in types
TypeScript Simple Types
Explicit Type
let firstName: string = "Dylan";
Implicit Type
let firstName = "Dylan";
Note: Having TypeScript "guess" the type of a value is called infer.
TypeScript Special Types
any会禁用类型检查:
let v: any = true;
v = "string"; // no error as it can be "any" type
Math.round(v); // no error as it can be "any" type
Type: unknown
跟any 有些像
Type: never
never
effectively throws an error whenever it is defined
let x: never = true; // Error: Type 'boolean' is not assignable to type 'never'.
Type: undefined & null
undefined
and null
are types that refer to the JavaScript primitives undefined
and null
respectively.
let y: undefined = undefined;
let z: null = null;
Arrays
const names: string[] = [];
names.push("Dylan"); // no error
Tuple
A tuple is a typed array
// define our tuple
let ourTuple: [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Coding God was here'];
Enums
An enum is a special "class" that represents a group of constants (unchangeable variables).
By default, enums will initialize the first value to 0
and add 1 to each additional value:
enum CardinalDirections {
North,
East,
South,
West
}
let currentDirection = CardinalDirections.North;
// logs 0
console.log(currentDirection);
// throws error as 'North' is not a valid enum
currentDirection = 'North'; // Error: "North" is not assignable to type 'CardinalDirections'.
functions
TypeScript has a specific syntax for typing function parameters and return values.
you can define types of parameters and function
function getTime(): number {
return new Date().getTime();
}
function multiply(a: number, b: number) {
return a * b;
}
Object
const car: { type: string, model: string, year: number } = {
type: "Toyota",
model: "Corolla",
year: 2009
};
Type Aliases
Type Aliases allow defining types with a custom name (an Alias).
Type Aliases can be used for primitives like string
or more complex types such as objects
and arrays
:
reusable
type CarYear = number
type CarType = string
type CarModel = string
type Car = {
year: CarYear,
type: CarType,
model: CarModel
}
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
year: carYear,
type: carType,
model: carModel
};
Interfaces
Interfaces are similar to type aliases, except they only apply to object
types.
interface Rectangle {
height: number,
width: number
}
const rectangle: Rectangle = {
height: 20,
width: 10
};
Union | (OR)
Using the |
we are saying our parameter is a string
or number
:
function printStatusCode(code: string | number) {
console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode('404');
Optional Chaining
Optional Chaining is a JavaScript feature that works well with TypeScript's null handling. It allows accessing properties on an object, that may or may not exist, with a compact syntax. It can be used with the ?.
operator when accessing properties.
他就像个可有可无的东西,标注了,他可以有也可以没有
React in Ts
https://www.youtube.com/watch?v=jrKcJxF0lAU
补充:
因为js 和ts 太像了,所以我总是写错代码。不知道怎么应用比较好。然后问了colin,他说,interface常会被使用,就是用来定义type的。