1.TS 变量声明

  1. boolean
  2. number
  3. string
  4. Array
  5. Any
  6. Null 和 Undefined
let isDone: boolean = false;
let decLiteral: number = 6;
let name: string = "bob";
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
let notSure: any = 4;
let u: undefined = undefined;
let n: null = null; 

6.enum 枚举类型,我一般很少用

enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;

2.接口声明

》TypeScript的核心原则之一是对值所具有的_结构_进行类型检查。先定义规则,按照规则形成数据。

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
  • 可选属性 (用?) 可以对属性预定义。

    • 有些是只在某些条件下存在,或者根本不存在
interface SquareConfig {
  color?: string;
  width?: number;
}
  • 只读属性(一些对象属性只能在对象刚刚创建的时候修改其值)
interface Point {
    readonly x: number;
    readonly y: number;
}
  • 描述函数类型的接口
export interface IButtonProps {
  title: string;
  type: string;
  className?: string;
  onClick?: () => void;
}

import './styles.scss';
const Button: FunctionComponent<IButtonProps> = ({title, type, className, onClick}) => {

  return (
    <button type="button" onClick={onClick} className={`btn ${type} ${className}`}>{title}</button>
  )
}
import Button from "@ui/Button";
<Button title={t("home:btn:title:txt")} type={"red"} onClick={() => {
            dispatch(actionSignOut())
          }} />

3. 函数申明

  • 一般情况下 定义

function identity(arg: number): number {
    return arg;
}

//HOOKS 一般这样写,我比较懒,简单能应用就行啦
const getPage = (BookNumObj: BookNum, props: any) => {
    const LOCAL_STORAGE: { LOCALE: string; CREDENTIALS_KEY: string } = {
      LOCALE: "app:locale",
      CREDENTIALS_KEY: "app:credentials",
    };
    

4. 范型

  • 可以使用泛型来创建可重用的组件,一个组件可以支持多种类型的数据
function identity<T>(arg: T): T {
    return arg;
}

木子喵
492 声望26 粉丝

too young, too naive