5 个有用的 TypeScript 技巧
1. 创建类型检查函数
interface IDog{
name: string;
age: number;
kidFriendly: boolean;
}
interface ICat{
name: string;
age: number;
activityLevel: number;
}
type Animal = IDog | ICat;
/** Is the animal a dog ? */
const isDog = (animal: Animal) : animal is IDog => (animal as IDog).kidFriendly !== undefined;
if(isDog(animal)){
console.log(animal.kidFriendly);
}
更多信息请见:
2. 将接口的所有属性设置为可选
interface IDog{
name: string;
age: number;
kidFriendly: boolean;
}
const dog : Partial<IDog> = {
name: "Rex"
}
3. 获取函数参数的类型
const walkDog = (dogName: string, distance: number) => { /** ... */ }
const params: Parameters<typeof walkDog> = ["Rex", 48];
4. 使用 Setter 和 Getter
Setter 和 Getter 也存在于纯 JavaScript 中。不过,它们在 TypeScript(以及其他语言)中非常有用。
class Dog{
private _name: string = "";
get name(): string{
return this._name;
}
/** Check the length of the name before setting it **/
set name(newName: string){
if(newName.length < 8) {
throw new Error(`The dog's name needs at least 8 charachters`)
}
this._name = newName;
}
}
5. 可选链式调用
可选链最近已添加到 JavaScript(ECMAScript 2020)。
let cat?: ICat;
/** With optional chaining **/
let animal = cat?.fur.length;
/** Without optional chaining **/
let cat = cat === null || cat === undefined ? undefined : car.fur.length;