【发布时间】:2026-01-04 22:15:01
【问题描述】:
如果接口 A 和接口 B 只有一个公共属性,则不会显示像这样的 typescript 编译器错误。为什么?
Type '{ a: string; c: number; }' is not assignable to type 'A'.
Object literal may only specify known properties, and 'c' does not exist in type 'A'.
此错误不仅应显示在 object literal 中,还应显示在 interface 中。
- 谁能回答以下问题? (第一季度、第二季度、第三季度)
- 有没有办法检查更严格?
interface A {
a?: string;
b?: number;
}
interface B {
a?: string;
c?: number;
}
interface C {
x?: string;
}
const f = (args: A[]) => {
console.log(args);
};
// (1) error: type check
const x = () => {
f([{ a: 'a', c: 1 }]);
};
// (2) no error. Q1. what is the difference between (1) and (2)?
const y = () => {
const args = [
{ a: 'a', c: 1 }
]
f(args);
};
// (3) error: A and C have no common property
const z = () => {
f([] as C[]);
};
// (4) no error. [Q2] what is the difference between (3) and (4)?
const w = () => {
f([] as B[]);
};
// (5) error: A and C have no common property
const u = () => {
f([{ x: 1 } as C]);
};
// (6) no error. [Q3] what is the difference between (5) and (6)?
const v = () => {
f([{ c: 1 } as B]);
};
【问题讨论】:
-
谢谢。但我认为这还不够。我编辑了我的问题,以便更容易理解我的问题。
标签: typescript compiler-errors