Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 模板参数推断中的TypeScript差异-类型交集与扩展类型_Javascript_Typescript_Types_Intersection_Extends - Fatal编程技术网

Javascript 模板参数推断中的TypeScript差异-类型交集与扩展类型

Javascript 模板参数推断中的TypeScript差异-类型交集与扩展类型,javascript,typescript,types,intersection,extends,Javascript,Typescript,Types,Intersection,Extends,在下面的玩具实验中(从现实世界的示例中简化),为什么根据模板是使用扩展类型实例化还是使用交叉类型实例化,模板参数的推导会有所不同 interface Base { b: number } interface Extra { a: string } interface Ext1 extends Extra { b: number } type Ext2 = Base & Extra // f returns a function that takes a T as input cons

在下面的玩具实验中(从现实世界的示例中简化),为什么根据模板是使用扩展类型实例化还是使用交叉类型实例化,模板参数的推导会有所不同

interface Base { b: number }
interface Extra { a: string }
interface Ext1 extends Extra { b: number }
type Ext2  = Base & Extra

// f returns a function that takes a T as input
const f = <T extends Base>(inp: T & Extra): ((arg: T) => void) => {
    return (arg: T) => console.log(inp.a + arg.b) 
}

const x1: Ext1 = { a: "x1", b: 1 }
const x2: Ext2 = { a: "y1", b: 2 } 

const f1 = f(x1) // T inferred to Ext1
const f2 = f(x2) // T inferred to Base, NOT Ext2 (why?)

const inp = { b: 3 }

// error Argument of type '{ b: number; }' is not assignable to parameter of type 'Ext1'. Property 'a' is missing in type '{ b: number; }' but required in type 'Ext1'.
const out1 = f1(inp) 

// ok since inp is of type Base
const out2 = f2(inp)
接口基{b:number}
接口额外{a:string}
接口Ext1扩展了额外的{b:number}
类型Ext2=基本和额外
//f返回一个以T为输入的函数
常量f=(输入:T和额外):((参数:T)=>void)=>{
return(arg:T)=>console.log(inp.a+arg.b)
}
常量x1:Ext1={a:x1',b:1}
常量x2:Ext2={a:y1',b:2}
常数f1=f(x1)//T推断为Ext1
常数f2=f(x2)//T推断为基数,而不是Ext2(为什么?)
常量inp={b:3}
//类型为“{b:number;}”的错误参数不能分配给类型为“Ext1”的参数。属性“a”在类型“{b:number;}”中丢失,但在类型“Ext1”中是必需的。
常数out1=f1(输入)
//可以,因为inp是Base类型
常数out2=f2(输入)