为什么我向接口添加额外属性时 TypeScript 不报错?

问题描述 投票:0回答:2
type MyType = {
  propertyOne: string
  propertyTwo: number
}

export const someFunction = (line: MyType[]): MyType[] => {
  return line.map((t) => ({
    ...t,
    someAdditionalProperty: 'why is this legal',
  }))
}

为什么这里允许有someAdditionalProperty?如何禁止它?

type MyType = {
  propertyOne: string
  propertyTwo: number
}

export const someFunction = (line: MyType[]): MyType[] => {
  const someVariable: MyType[] =  line.map((t): MyType => ({
    ...t,
    someAdditionalProperty: 'why is this legal',
  }))
  return someVariable
}

这有点抱怨,但使用 map 或任何其他 Array.prototype 函数对我的所有函数执行此操作似乎仍然需要大量工作。

typescript
2个回答
0
投票

Typescript 允许这样做,因为它使用 structural subtyping。只要给定类型具有预期类型的所有成员,它就是兼容的。 Typescript 只会在非常有限的情况下出错额外的属性。

允许这样做也有充分的理由,否则不可能发生这样的事情:

interface Pet {
  owner: string
}

interface Dog extends Pet {
  name: string
}

function owner(pet: Pet): string {
  return pet.owner;
}

const fluffy: Dog = { owner: "John", name: "Fluffy" }

// This is only possible due to subtyping
const fluffyOwner = owner(fluffy);

0
投票

使用

const
变量语法打字稿会尝试在计算之前检查类型。但是如果你只使用箭头函数没有预先计算的结果来检查,那就很奇怪了。

所以解决方案是使用

typescript 4.9
及以上版本,并使用名为
satisfies
的新功能正是针对这种情况。

你的代码:

export const someFunction = (line: MyType[]) => {
  return line.map<MyType>((t) => ({
    ...t,
    someAdditionalProperty: 'why is this legal',
  } satisfies MyType))
}

现在显示错误的输入错误。

© www.soinside.com 2019 - 2024. All rights reserved.