![](/img/trans.png)
[英]Typescript: type safety for interface properties in a function declaration
[英]Typescript union type inside a interface function declaration
Type '(param: CountryCodeItem) => void' is not assignable to type '(param: Item) => void'.
Types of parameters 'param' and 'param' are incompatible.
Type 'Item' is not assignable to type 'CountryCodeItem'.
Type 'BasicItem' is missing the following properties from type 'CountryCodeItem': abbreviation, code(2322)
无法理解为什么我会收到上述错误? 即使发生错误,为什么在下面指定的示例中只在案例 1 中而不是在案例 2 中
案例 1:Function 在接口内部通过箭头 function 定义导致错误
案例 3:而不是箭头 function 定义使用定义 function 的经典方法,它工作正常
export interface CountryCodeItem {
id: number;
label: string;
abbreviation: string;
code: number;
}
interface BasicItem {
label: string;
id: number;
}
export type Item = BasicItem | CountryCodeItem;
//Case 1
interface Case1 {
fn : (param:Item)=>void
}
const case1 :Case1 = {
fn :(param: CountryCodeItem) => {
console.log("a")
}
}
//Case 2
const case2Fn=(a: Item) => {
console.log("a")
}
const abc: CountryCodeItem= {
id: 10,
label: "a",
abbreviation: "a",
code:10
}
case2Fn(abc)
//Case 3
interface Case3 {
fn(param:Item):void
}
const case3 :Case3 = {
fn :(param: CountryCodeItem) => {
console.log("a")
}
}
游乐场链接链接
Case1是继承接口。 所以类型必须相同。 所以下面的代码是正确的,因为 Item 与 BasicItem | 相同国家代码项。
const case1 :Case1 = {
fn :(param: BasicItem | CountryCodeItem) => {
console.log("a")
}
}
Case2 是 function 参数。 所以参数只需要 toBasicItem 或 CountryCodeItem。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.