返回文章列表
0 字 · 1 分钟

TypeScript基本用法

· 编辑文章
// 声明 StatusType 类型
type StatusType = 0 | 1 | 2 | 3;

// 声明 currentRowData 的类型
interface RowData {
  status: StatusType;
  // 如果有其他属性,可以继续声明,比如 name, age 等
  // name: string;
  // age: number;
}

// 示例数据
const currentRowData: RowData = {
  status: 2,
  // name: "John Doe",
  // age: 30,
};
// 声明 getEditType 函数,返回值为 0 | 1 | 2
const getEditType = (status: StatusType): 0 | 1 | 2 => {
  if (status === 0) {
    return 0;
  }
  if (status === 1) {
    return 1;
  }
  if (status === 2 || status === 3) {
    return 2;
  }
  throw new Error('status is not in [0, 1, 2, 3]');
};
// 调用 getEditType 函数
const editType = getEditType(currentRowData.status);

console.log(editType);  // 输出 2

评论

无需注册,填写昵称即可评论 阅读 — 次