typescript - 如何告诉 Typescript 从一个不太严格的接口(interface)转换到一个更严格的接口(interface)是可以的?

标签 typescript

我试图让我粘贴在下面的代码执行,但 Typescript 编译器似乎不相信我已经正确地确保一个接口(interface)可以根据我所做的检查转换为另一个接口(interface)。我需要做什么才能让它对这段代码满意?


interface Person {
  name: string,
  address?: string
}

interface PersonWithAddress extends Person {
  address: string
}

function tryLoggingAddresses(people: Array<Person>) {
  people.forEach(person => {
    if (person.address) {
      logAddress(person)
    }
  })
}

function logAddress(personWithAddress: PersonWithAddress) {
  console.log(personWithAddress.address)
}

typescript 错误:

error TS2345: Argument of type 'Person' is not assignable to parameter of type 'PersonWithAddress'.
      Types of property 'address' are incompatible.
        Type 'string | undefined' is not assignable to type 'string'.
          Type 'undefined' is not assignable to type 'string'.

    63       logAddress(person)

我知道我可以通过将行更改为 logAddress(person as PersonWithAddress) 来强制转换,但这实际上禁用了所有不理想的类型检查。如果没有那个,有没有办法做到这一点?

最佳答案

您可以使用 type guard代替您现有的条件表达式。这将有助于通知编译器数据结构满足您在 control flow analysis 期间想要的标准。 .

TypeScript Playground

function personHasAddress (person: Person): person is PersonWithAddress {
  return typeof person.address === 'string';
}

function logAddresses (people: Person[]) {
  for (const person of people) {
    if (personHasAddress(person)) logAddress(person);
  }
}

关于typescript - 如何告诉 Typescript 从一个不太严格的接口(interface)转换到一个更严格的接口(interface)是可以的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72705744/

相关文章:

javascript - View中输入类型="time"的值的变化没有反射(reflect)在Angular的Model中

带对象的 TypeScript 枚举

node.js - 如何动态更改 Mongoose 提供程序中集合或数据库的名称,Nestjs?

jquery - jquery 方法上的对象可能未定义

node.js - Angular - 将 Json 对象传递给显示 [Object Object] 的子对象

javascript - 如何使用 moment 将时间转换为百分比

javascript - 使用reduceRight删除数组中的最后一个元素

angular - 如何在 Angular 2 中使用 getter 和 setter 实现 BehaviorSubject

typescript - STRIPE + TypeScript : TypeError: stripe_1. 默认不是构造函数

javascript - 动画化动态 Angular 组件的移除?