Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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
Typescript:如何在保存记录的结构上“应用”?_Typescript_Typescript Typings - Fatal编程技术网

Typescript:如何在保存记录的结构上“应用”?

Typescript:如何在保存记录的结构上“应用”?,typescript,typescript-typings,Typescript,Typescript Typings,假设我们有一个保存记录的结构,我们希望在其上应用,另一个保存记录的结构用于第一个结构的键。(基本上与Applyfantasylandspec相反) 让我们首先定义一些我们将使用的类型: 类型索引=字符串|编号|符号 类型结构={ 只读值:R apOn:(fab:Struct B}>)=> 结构 } 然后处理结构本身 声明函数newStruct(值:R):结构 const struct=newStruct({a:1,b:true}) 当为apOnmethods参数指定一个Struct时,前两个

假设我们有一个保存记录的结构,我们希望
在其上应用
,另一个保存记录的结构用于第一个结构的键。(基本上与
Apply
fantasylandspec相反)

让我们首先定义一些我们将使用的类型:

类型索引=字符串|编号|符号
类型结构={
只读值:R
apOn:(fab:Struct B}>)=>
结构
}
然后处理结构本身

声明函数newStruct(值:R):结构
const struct=newStruct({a:1,b:true})
当为
apOn
methods参数指定一个
Struct
时,前两个te与预期一样工作,该参数具有相同数量的键,并且具有相同返回类型的函数

constwithfuncsa=newStruct({
a:(a:number)=>`${a}`,
b:(a:boolean)=>`${a}`,
})
const withFuncsb=新结构({
答:(a:数字)=>a>0,
})
const resa=struct.apOn(withFuncsa).value//如预期{a:string,b:string}
const resb=struct.apOn(withFuncsb).value//如预期{a:boolean,b:boolean}
但返回类型不同时会中断:

const with funcsc=newStruct({
答:(a:数字)=>a>0,
b:(a:boolean)=>`${a}`,
})
const resc=struct.apOn(with funcsc).value
//中断会导致此withFuncc函数的所有返回类型都相同
//应为{a:boolean,b:string}

它们是让它与不同的返回类型一起工作的一种方式吗?

我们需要修改签名,以推迟决定
B
,直到它计算的密钥已知为止

type Struct<R extends Record<Index, any>> = {
  readonly value: R
  apOn: <F extends {[K in keyof Partial<R>]: (a: R[K], k: K) => any}>
      (fab: Struct<F>) =>  
          Struct<Omit<R, keyof F> & {[K in keyof F]: ReturnType<F[K]>}>
}

const t: {strings: string[], bools: boolean[]} = {
    strings: [resa.a, resa.b, resc.b],
    bools: [resb.a, resb.a, resc.a],
}