Typescript 如何键入从对象返回位于属性中的数组中的单个元素的函数
我有这个功能Typescript 如何键入从对象返回位于属性中的数组中的单个元素的函数,typescript,typescript-generics,Typescript,Typescript Generics,我有这个功能 function single<T, TElem, K extends keyof T>(obj: T, name: K): TElem { const source = obj[name]; if (source.length !== 1) { throw Error(`Debería existir exactamente un ${name} asociado`); } return _.first(source); } 功能单一(obj
function single<T, TElem, K extends keyof T>(obj: T, name: K): TElem {
const source = obj[name];
if (source.length !== 1) {
throw Error(`Debería existir exactamente un ${name} asociado`);
}
return _.first(source);
}
功能单一(obj:T,名称:K):远程{
const source=obj[name];
if(source.length!==1){
抛出错误(`Debería existir execamente un${name}asociado`);
}
返回第一个(源);
}
函数的思想是返回数组中的唯一值,该数组位于原始对象的指定属性中。问题是我不知道如何用这样的东西键入该函数:
function single<T, TElem, K extends keyof T>(obj: T, name: K): TElem
where T[K] extends TElem[]
{
const source = obj[name];
if (source.length !== 1) {
throw Error(`Debería existir exactamente un ${name} asociado`);
}
return _.first(source);
}
function single<K extends PropertyKey, T extends Record<K, any[]>>(
obj: T,
name: K
): T[K][number] {
const source = obj[name];
if (source.length !== 1) {
throw Error(`Debería existir exactamente un ${name} asociado`);
}
return source[0];
}
功能单一(obj:T,名称:K):远程
其中T[K]扩展了TElem[]
{
const source=obj[name];
if(source.length!==1){
抛出错误(`Debería existir execamente un${name}asociado`);
}
返回第一个(源);
}
有没有办法做到这一点?我倾向于使用这样的打字方式:
function single<T, TElem, K extends keyof T>(obj: T, name: K): TElem
where T[K] extends TElem[]
{
const source = obj[name];
if (source.length !== 1) {
throw Error(`Debería existir exactamente un ${name} asociado`);
}
return _.first(source);
}
function single<K extends PropertyKey, T extends Record<K, any[]>>(
obj: T,
name: K
): T[K][number] {
const source = obj[name];
if (source.length !== 1) {
throw Error(`Debería existir exactamente un ${name} asociado`);
}
return source[0];
}
我觉得不错。好吧,希望这会有帮助;祝你好运