Skip to content

类型 Compatibility

一句话解释

类型 compatibility 是规则 TypeScript uses 到 determine 如果值 的 one 类型能 是 assigned 到变量的 another 类型, based on 结构输入.

用大白话说

Type compatibility determines whether TypeScript allows assigning a value of type A to a variable of type B. TypeScript uses structural typing: A is compatible with B if A has all the properties that B requires.

例如, { name: 字符串; age: 数字 } is compatible with { name: 字符串 } because it has all required properties (and more). This is called "excess 属性检查" in reverse — having extra properties is fine for assignment, but not for object literals.

Type compatibility also applies to functions (parameter bivariance), arrays (covariance), and generics. Understanding these rules helps you write types that accept the right range of values.

示例

typescript
interface Person { name: string; }
interface Employee { name: string; salary: number; }

const emp: Employee = { name: "Bob", salary: 50000 };
const person: Person = emp; // OK: Employee has all Person properties

Employee 是 compatible 使用 Person 因为它 有所有的 Person's 必需属性.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表