tagListModel.ts

  1. const localStorageName = 'tags';
  2. // 定义类型
  3. type tagListModel = {
  4. data: string[];
  5. // 函数写参数类型和返回值类型
  6. fetch: ()=>string[];
  7. save: ()=> void; // void代表不返回
  8. create: (name: string)=> string;
  9. }
  10. // 用定义的类型声明变量
  11. const tagListModel:tagListModel = {
  12. data: [],
  13. fetch() {
  14. this.data = JSON.parse(window.localStorage.getItem(localStorageName) || '[]') as string[];
  15. return this.data
  16. },
  17. save() {
  18. window.localStorage.setItem(localStorageName, JSON.stringify(this.data));
  19. },
  20. create(name) {
  21. this.data.push(name);
  22. this.save();
  23. return name;
  24. }
  25. };
  26. export default tagListModel;

判断标签重复

方法1:用error信息

  1. create(name) {
  2. // 如果重复,抛出错误
  3. if(this.data.indexOf(name)>= 0) throw new Error("duplicated")
  4. this.data.push(name);
  5. this.save();
  6. return name;
  7. }
  1. createTag() {
  2. const name = window.prompt('请输入标签名');
  3. if (name) {
  4. try {
  5. tagListModel.create(name);
  6. } catch (error) {
  7. // 获取错误信息
  8. if (error.message === 'duplicated') {
  9. window.alert('标签名重复');
  10. }
  11. }
  12. }
  13. }

方法2:直接返回string,根据信息给出提示

方法3:使用联合类型(string的子集)

  1. const localStorageName = 'tags';
  2. type tagListModel = {
  3. ...
  4. create: (name: string)=> "success" | "duplicated"; // 联合类型,几个字符串中的一个
  5. }
  6. const tagListModel:tagListModel = {
  7. ...
  8. create(name) {
  9. if(this.data.indexOf(name)>= 0) return "duplicated";
  10. this.data.push(name);
  11. this.save();
  12. return "success";
  13. }
  14. };
  15. export default tagListModel;
  1. createTag() {
  2. const name = window.prompt('请输入标签名');
  3. if (name) {
  4. const message = tagListModel.create(name);
  5. // 根据返回的信息给出提示
  6. if (message === 'duplicated') {
  7. window.alert('标签名重复');
  8. } else if (message === 'success') {
  9. window.alert('创建成功');
  10. }
  11. }
  12. }