分享
三行代码  ›  专栏  ›  技术社区  ›  Vic

在TypeScript中,我们可以为函数数组创建可重用的接口吗?

  •  1
  • Vic  · 技术社区  · 1 周前

    我有Vue+Typescript,想知道是否有更好的方法来描述函数数组的类型。我现在有以下代码。我能定义一个 formRules 接口而不是重新声明类型 Array<(v: string) => boolean | string> 甚至只是 <(v: string) => boolean | string>

    <script lang="ts">
    import { Vue, Component } from 'vue-property-decorator';
    
    @Component({
      name: 'signUpForm',
    })
    
    export default class SignUpForm extends Vue {
      private valid = true
    
      private firstName = ''
      private lastName = ''
      private nameRules: Array<(v: string) => boolean | string> = [
        (v) => !!v || 'Name is required',
      ]
    
      private email = ''
      private emailRules: Array<(v: string) => boolean | string> = [
        (v) => !!v || 'E-mail is required',
        (v) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
      ]
    }
    </script>
    
    3 回复  |  直到 1 周前
        1
  •  1
  •   klugjo    1 周前

    可以创建与函数签名相等的类型。

    <script lang="ts">
    import { Vue, Component } from 'vue-property-decorator';
    
    @Component({
      name: 'signUpForm',
    })
    
    type FormFunction = (v: string) => boolean | string;
    
    export default class SignUpForm extends Vue {
      private valid = true
    
      private firstName = ''
      private lastName = ''
      private nameRules: FormFunction[] = [
        (v) => !!v || 'Name is required',
      ]
    
      private email = ''
      private emailRules: FormFunction[]*emphasized text* = [
        (v) => !!v || 'E-mail is required',
        (v) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
      ]
    }
    </script>
    

    export default class SignUpForm extends Vue {
      private valid = true
    
      private firstName = ''
      private lastName = ''
      private nameRules = [
        (v: string) => !!v || 'Name is required',
      ]
    
      private email = ''
      private emailRules = [
        (v: string) => !!v || 'E-mail is required',
        (v: string) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
      ]
    }
    

    这将是最干净的方法,使用较少不必要的类型定义。

        2
  •  2
  •   lei li    1 周前
    type CheckFunc={(v:string):boolean|string}
    
    type ArrCheckFunc=CheckFunc[]
    
    
    let formRules:CheckFunc[]
    //or
    let formRules:ArrCheckFunc
    
        3
  •  0
  •   Tulshi Das    1 周前

     type fArr = ((v:string)=>boolean | string)[];
     let x:fArr;
     x=[(v:string)=>v];
     x[0]("h");