Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.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 - Fatal编程技术网

Typescript 使用数组进行类型解析

Typescript 使用数组进行类型解析,typescript,Typescript,我正在寻找一种具有以下函数签名的方法: type fn = <T>(fields : (keyof T)[]) => { [key in fields] : any } type fn=(字段:(keyof T)[])=>{[key-in-fields]:any} 这将产生如下类型检查 const StructureType = { a: 1, b: 2, } // the fields argument is strictly type checked

我正在寻找一种具有以下函数签名的方法:

type fn = <T>(fields : (keyof T)[]) => { [key in fields] : any }
type fn=(字段:(keyof T)[])=>{[key-in-fields]:any}
这将产生如下类型检查

const StructureType = {
    a: 1,
    b: 2,
}

// the fields argument is strictly type checked
// this fails because c not in keyof T
const x = fn<typeof StructureType>(['c'])

// this works
const x = fn<typeof StructureType>(['a'])
// x should be of type = { a : any }
// function parameter
const StructureType={
答:1,,
b:2,
}
//fields参数经过严格的类型检查
//这会失败,因为c不在T键中
常数x=fn(['c'])
//这很有效
常数x=fn(['a'])
//x的类型应为={a:any}
//函数参数
如果您链接泛型,那么它可以工作,但是您必须手动传递多个泛型类型

type fn = <T, TField extends keyof T>(fields : TField[]) => { [key in TField] : any }

// cannot call like this, throws error missing arguments
const x = fn<StructureType>(['a'])
type fn=(字段:TField[])=>{[key in TField]:any}
//无法这样调用,抛出错误缺少参数
常数x=fn(['a'])
如果将类型作为参数传递,则可以消除泛型def,但随后将一个未使用的参数传递给函数:

type fn = <T, TField extends keyof T>(structType : T, fields : TField[]) => { [key in TField] : any }

// works
const x = fn(StructureType, ['a'])
type fn=(structType:T,fields:TField[])=>{[key-in-TField]:any}
//工作
常数x=fn(结构类型,['a'])
我发现的另一种有效方法是将函数链接在一起:

type fn = <T>() => <TField extends keyof T>(fields : TField[]) => { [key in TField] : any }

// this works
const x = fn<StructureType>()(['a'])
type fn=()=>(字段:TField[])=>{[key in TField]:any}
//这很有效
常数x=fn()
但显然这不是最好的解决方案,因为它会创建一个不必要的额外函数

有没有一种方法可以实现我想要的,而不需要额外的、不必要的代码