Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/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_Generics - Fatal编程技术网

Typescript:按接口属性与自身值匹配进行类型筛选

Typescript:按接口属性与自身值匹配进行类型筛选,typescript,generics,Typescript,Generics,要将第一个参数的筛选类型设置为第二个参数的筛选类型吗 请检查以下代码: 接口类型带标签{ 标签:字符串; 列表:字符串; } 接口A扩展了TypeWithLabel{ 标签:"a";; 列表:“1”|“2”|“3”; } 接口B扩展了TypeWithLabel{ 标签:"b";; 列表:“4”|“5”|“6”; } 类型TypeProperty=T[U]; 功能ab( 标签:U, 项目:TypeProperty ) { } //想要得到一个只有标签“A”的 //然后为项目显示“1”|“2”|“3

要将第一个参数的筛选类型设置为第二个参数的筛选类型吗

请检查以下代码:

接口类型带标签{
标签:字符串;
列表:字符串;
}
接口A扩展了TypeWithLabel{
标签:"a";;
列表:“1”|“2”|“3”;
}
接口B扩展了TypeWithLabel{
标签:"b";;
列表:“4”|“5”|“6”;
}
类型TypeProperty=T[U];
功能ab(
标签:U,
项目:TypeProperty
) {
}
//想要得到一个只有标签“A”的
//然后为项目显示“1”|“2”|“3”
ab('a','1');//对的
ab('a','4');//错误
//只想获得标签为“B”的B
//然后为项目显示“4”|“5”|“6”
ab('b','4');//对的
ab('b','1');//错误
也许,还有其他方法可以过滤接口吗?
我曾考虑过如何重用泛型,但函数中需要将
标签
作为字符串值。

不确定,如果我理解正确-如果希望将函数
ab
的范围限定为
A
B
,则泛型类型参数也应反映此要求。您需要将代码更改为:

// given A, restrict item to '1' | '2' | '3'
ab<A>("a", "1"); // ok
ab<A>("a", "4"); // error (ok)

// given A, restrict item to '4' | '5' | '6'
ab<B>("b", "4"); // ok
ab<B>("b", "1"); // error (ok)

type LabelToList = {
  a: A;
  b: B;
};

function ab<K extends keyof LabelToList>(
  label: K,
  item: LabelToList[K]["list"]
) {}