我有Vue + Typescript,正在尝试确定是否有更好的方法来描述函数数组的类型。我目前有以下代码。我可以定义一个class App extends Component {
constructor() {
super();
this.state = {
todo_lists: [
{ id: 1, name: "Hoc React" },
{ id: 2, name: "Hoc HTML" },
{ id: 3, name: "Hoc Jquery" },
{ id: 4, name: "Hoc CSS" }
],
showList : []
};
}
componentDidMount(){
let {showList, todo_lists} = this.state
this.setState({
showList : [...todo_lists]
})
console.log(showList)
}
}
接口,而不是重新声明类型formRules
甚至只声明Array<(v: string) => boolean | string>
吗?
<(v: string) => boolean | string>
答案 0 :(得分:2)
type CheckFunc={(v:string):boolean|string}
type ArrCheckFunc=CheckFunc[]
let formRules:CheckFunc[]
//or
let formRules:ArrCheckFunc
答案 1 :(得分: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>
作为旁注,您不必完全指定类型,因为TypeScript能够自行确定其类型。如果Typescript不知道它是什么,只需指定参数v的类型:
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 :(得分:0)
作为一个简单的例子-
type fArr = ((v:string)=>boolean | string)[];
let x:fArr;
x=[(v:string)=>v];
x[0]("h");