我想在.ts文件中定义必填字段我尝试使用此代码,但它无法正常工作。
class Person {
required(FirstName: string);
}
答案 0 :(得分:0)
简单:
class Person {
FirstName: string;
}
var foo:Person = {}; // Error `FirstName` is required
答案 1 :(得分:0)
如果您对运行时验证感兴趣,则必须自己编写验证。你可以选择:
class Person {
public firstName:string;
constructor(firstName: string) {
// You can add any validation you want here.
if (!firstName) {
throw new Error("Invalid name!");
}
this.firstName = firstName;
}
}
let p = new Person(null); // throws an error
或
class Person {
public firstName:string;
validateData() {
if (!this.firstName) {
throw new Error("Invalid name!");
}
}
}
let p = new Person();
p.validateData(); // throws an error
PS:我建议先学习TypeScript handbook,因为如果你从TypeScript开始,它很可能会回答你的所有问题。