# Ts 使用指南
## 6、参数类型和返回类型
```ts
// 参数类型和返回类型
function createUserId(name: string, id: number): string { // fn xx(a:参数类型): 返回类型 {}
return name + id;
}
// 只读属性
interface Person {
readonly name: string;
age?: number;
}
// 任意属性
interface Person {
name: string;
age?: number;
[propName: string]: any;
}
// 方法类型
// 没有返回值
type SetPoint = (x: number, y: number) => void;
interface SetPoint {
(x: number, y: number): void;
}
// 有返回值
type SetPoint1 = (x: number, y: number) => string;
interface SetPoint1 {
(x: number, y: number): string;
}
// 泛型语法
function identity <T, U>(value: T, message: U) : T {
console.log(message);
return value;
}
console.log(identity<Number, string>(68, "Semlinker"));
```
## 5、联合类型
* 联合类型
```ts
// 联合类型通常与 null 或 undefined 一起使用:
const sayHello = (name: string | undefined) => {
/* ... */
};
// 用来约束取值只能是某几个值中的一个
let num: 1 | 2 = 1;
type EventNames = 'click' | 'scroll' | 'mousemove';
// 类型联合
interface Motorcycle {
vType: "motorcycle"; // discriminant
make: number; // year
}
interface Car {
vType: "car"; // discriminant
transmission: CarTransmission
}
interface Truck {
vType: "truck"; // discriminant
capacity: number; // in tons
}
type Vehicle = Motorcycle | Car | Truck;
```
## 4、类型守卫
* 1、自定义类型保护的类型谓词
```ts
function isNumber(x: any): x is number {
return typeof x === "number";
}
function isString(x: any): x is string {
return typeof x === "string";
}
```
## 3、确定赋值断言
```ts
let x: number;
initialize();
// Variable 'x' is used before being assigned.(2454)
console.log(2 * x); // Error
function initialize() {
x = 10;
}
```
```ts
let x!: number;
initialize();
console.log(2 * x); // Ok
function initialize() {
x = 10;
}
```
## 2、非空断言
* 1、忽略 undefined 和 null 类型
```ts
function myFunc(maybeString: string | undefined | null) {
const ignoreUndefinedAndNull: string = maybeString!; // Ok
}
```
* 2、调用函数时忽略 undefined 类型
```ts
type NumGenerator = () => number;
function myFunc(numGenerator: NumGenerator | undefined) {
const num2 = numGenerator!(); //OK
}
```
## 1、类型断言
* 1.“尖括号” 语法
```ts
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
```
* 2.as 语法
```ts
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
```
* 3、变量类型
```ts
const many: any = $100; // 不确定类型用any
const arr: Array<number> = [1, 2];
const arr: number[] = [1, 2];
const arr: any[] = [1, false, 'yellow'];
const arr: object = {name:'张三', sex: '男'};
```
-end-