跳到正文
当下的七炎
返回

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

编辑文章
分享这篇文章:

评论

使用 GitHub 账号登录后即可评论


上一篇
TypeScript 与 React 结合常见的用法
下一篇
什么叫做5W2H法