Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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,我想知道在typescript中是否可以有如下内容: func<T,V>(prop: keyof T: V) interface IIntf{ prop1: string, prop2: number } func<IIntf, string>(‘prop1’) //OK func<IIntf, string>(‘prop2’) //NOT OK (prop2 is of type number) func(prop:keyof T:V) 接口I

我想知道在typescript中是否可以有如下内容:

func<T,V>(prop: keyof T: V)

interface IIntf{
  prop1: string,
  prop2: number
}

func<IIntf, string>(‘prop1’) //OK
func<IIntf, string>(‘prop2’) //NOT OK (prop2 is of type number)
func(prop:keyof T:V)
接口IIntf{
prop1:字符串,
prop2:数字
}
func('prop1')//确定
func('prop2')//不正常(prop2的类型为number)

这可以使用映射类型和类型推断,如以下类型中仅提取具有指定类型的键:

type ObjectKeysWithType<T, V> = {
    [K in keyof T]: T[K] extends V ? K : never
}[keyof T];
type ObjectKeysWithType={
[K in keyof T]:T[K]扩展V?K:从不
}[keyof T];
这里的理由是:

  • 仅当值与所需类型(
    V
    )匹配时,才将类型(使用映射类型)映射到值
  • 使用
    {..}[keyof T