TypeScript 中的接口类型检查

Shuvayan Ghosh Dastidar 2023年1月30日
  1. TypeScript 中的类型保护
  2. 在 TypeScript 中使用 typeof 来检查类型
  3. 在 TypeScript 中使用 instanceof
  4. 在 TypeScript 中使用 in 关键字来检查类型
TypeScript 中的接口类型检查

接口是 TypeScript 的重要组成部分,用于将类型与 TypeScript 中的变量和元素相关联,以确保类型安全,从而避免运行时错误。类和其他接口可以实现接口,因此这可以用于实际代码中的动态行为。

因此,有时可能需要知道实际的接口类型以确保类型安全,就像 Java 中的 instanceof 关键字一样。本教程将演示如何检查接口的类型以确保类型安全。

TypeScript 中的类型保护

类型保护是对 TypeScript 中存在的不同类型的检查,以确保类型安全。它是条件语句的形式。

当某种类型是一种或多种类型的组合时尤其需要。可以使用各种关键字来检查接口,例如 typeofinstanceofin,甚至可以制作自定义类型保护。

interface Animal {
    name : string;
    legs : number;
    eyes : number;
}

interface Dog extends Animal {
    bark : () => void
}

interface Cat extends Animal {
    meow : () => void;
}

function getAnimal() : Dog | Cat {
    let choice = Math.random();
    if ( choice > 0.5){
        const dog : Dog = {
            name : 'Labrador',
            legs : 4,
            eyes : 2,
            bark : () => console.log("Woof")
        }
        return dog;
    }else {
        const cat : Cat = {
            name : 'Labrador',
            legs : 4,
            eyes : 2,
            meow : () => console.log("Meow")
        }
        return cat;
    }
}

const animal = getAnimal();
// Property 'meow' does not exist on type 'Dog | Cat'.
animal.meow();
// Property 'bark' does not exist on type 'Dog | Cat'.
animal.bark();

在上面的示例中,属性 meowbark 函数无法解析,因为 TypeScript 编译器不确定要推断什么。getAnimal 函数返回两种类型的联合,Dog | Cat,这会使编译器感到困惑。

必须引入类型保护或类型检查以使编译器理解适当的类型。

if ( 'meow' in animal){
    animal.meow();
} else if ( 'bark' in animal){
    animal.bark();
}

以上是如何强制执行类型检查以确保类型安全的示例。meowbark 属性是否存在于 animal 对象中并被相应地调用。

在 TypeScript 中使用 typeof 来检查类型

typeof 关键字可用于确定变量的类型;但是,它的范围非常有限。它可用于检查原始类型。

typeof 关键字返回的值可以是 stringnumberbigintbooleansymbolundefinedobjectfunction

typeof 关键字将所有复杂类型和 null 值作为对象返回。

const displayBill = ( amount : string | number ) => {
    if ( typeof amount === 'string') {
        amount = Number(amount);
    }
    let tax = (18.5 * amount) / 100;
    console.log('Bill : '+ amount + " $");
    console.log('Tax : '+ tax + " $");
    console.log('Total Payable : '+ (amount + tax) + " $");

}

displayBill(23.5);

输出:

"String conversion being done!"
"Bill : 23.5 $"
"Tax : 4.3475 $"
"Total Payable : 27.8475 $"

因此在上面的例子中,typeof 关键字被用来检查变量 amount 的类型,并且在检查之后进行了转换。这个检查对于计算 tax 变量是必要的,它要求 amountnumber 类型。

在 TypeScript 中使用 instanceof

instanceof 关键字检查与某些类对应的变量。以下类型保护用于那些被实例化为类对象的变量。

class User {
    name : string;
    amountDue : number;
    constructor( name : string, amount : number){
        this.name = name;
        this.amountDue = amount;
    }
}

class UserCredit extends User {
    constructor( user : User) {
        super(user.name, user.amountDue);
    }
    generateCredit(amount : number) {
        this.amountDue += amount;
        return this.amountDue;
    }
}

class UserDebit extends User {
    constructor( user : User) {
        super(user.name, user.amountDue);
    }
    settleDebt(){
        this.amountDue = 0;
    }
}

const TransactionSystem = () => {
    const user : User = {
        name : 'Alex',
        amountDue : 0
    }
    const option = Math.random();
    if ( option > 0.5) {
        // settle debts
        const userDebt = new UserDebit(user);
        userDebt.settleDebt();
        return userDebt;
    } else {
        // increase credit
        const userCredit = new UserCredit(user);
        userCredit.generateCredit(500);
        return userCredit;
    }
}

const UserTransaction = TransactionSystem();
if ( UserTransaction instanceof UserDebit) {
    console.log('Credit balance successfully debited');
} else if (UserTransaction instanceof UserCredit) {
    console.log("Credit limit increased")
}

在 TypeScript 中使用 in 关键字来检查类型

in 可用于检查某个属性是否存在于类型或接口中,因此可以与诸如 if-else 之类的条件语句一起使用来检查类型,从而采取行动并执行进一步的操作。下面显示了如何实现这一点的示例。

interface Person {
    name : string;
    age : number;
}
const person : Person = {
    name : "Alex",
    age : 30
}
console.log("name" in person); // true
console.log("address" in person); // false
Shuvayan Ghosh Dastidar avatar Shuvayan Ghosh Dastidar avatar

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

LinkedIn Website

相关文章 - TypeScript Interface