Typescript 根据参数确定类型

Typescript 根据参数确定类型,typescript,Typescript,我有一个函数,它调用外部api并根据发送的参数返回数据。我正在尝试键入此函数,但有一些困难 从“axios”导入axios; 接口IGetContactArgs{ 属性?:字符串[]; } 接口响应{ 身份证号码:, 特性:{ [索引:字符串]:任意; } } 常量getContact=(id:编号,参数?:IGetContactArgs)=>{ 返回axios.get(`URL/${id}`,{params}); } 调用此函数的一个示例是 const data=wait getContac

我有一个函数,它调用外部api并根据发送的参数返回数据。我正在尝试键入此函数,但有一些困难

从“axios”导入axios;
接口IGetContactArgs{
属性?:字符串[];
}
接口响应{
身份证号码:,
特性:{
[索引:字符串]:任意;
}
}
常量getContact=(id:编号,参数?:IGetContactArgs)=>{
返回axios.get(`URL/${id}`,{params});
}
调用此函数的一个示例是

const data=wait getContact(0,{properties:['name','img']});
这将返回

{
“id”:0,
“财产”:{
“姓名”:“约翰”,
“img”:https://imageurl.com/image",
}
}

有没有比我现在所做的更好的方法来键入它,从而使结果对象的类型由函数的输入决定

是的,可以更好。您可以使用[generics][1]来实现这一点

在我看来,您正在传递某个类型的属性。比如说内容

您可以根据
内容
类型定义属性在数组中采用的值以及响应类型

我只是提取了参数中的给定类型并将其分配给响应



Content
type确保不能使用泛型将一些随机字符串传递到属性中



是的,可以更好。您可以使用[generics][1]来实现这一点

在我看来,您正在传递某个类型的属性。比如说内容

您可以根据
内容
类型定义属性在数组中采用的值以及响应类型

我只是提取了参数中的给定类型并将其分配给响应



Content
type确保不能使用泛型将一些随机字符串传递到属性中



你的意思有点不清楚,但是如果你喜欢这个

function getContact<T extends number, S extends string>(
  id: T,
  params: { properties: S[] }
): {
  id: T;
  properties: {
    [K in S]: string;
  };
} {
  return {} as any;
}

// type is { id: 0; properties: { "hi": string; "you": string; } }
const u = getContact(0, { properties: ["hi", "you"] });
函数getContact(
id:T,
参数:{properties:S[]}
): {
id:T;
特性:{
[K in S]:字符串;
};
} {
返回{}如有;
}
//类型为{id:0;属性:{“hi”:string;“you”:string;}
const u=getContact(0,{properties:[“hi”,“you”]});

然后,所有类型都将从调用中推断出来,而无需编写任何其他接口。

您的意思有点不清楚,但如果您这样做的话

function getContact<T extends number, S extends string>(
  id: T,
  params: { properties: S[] }
): {
  id: T;
  properties: {
    [K in S]: string;
  };
} {
  return {} as any;
}

// type is { id: 0; properties: { "hi": string; "you": string; } }
const u = getContact(0, { properties: ["hi", "you"] });
函数getContact(
id:T,
参数:{properties:S[]}
): {
id:T;
特性:{
[K in S]:字符串;
};
} {
返回{}如有;
}
//类型为{id:0;属性:{“hi”:string;“you”:string;}
const u=getContact(0,{properties:[“hi”,“you”]});
然后,将从调用中推断出所有类型,而无需编写任何其他接口

function getContact<T extends number, S extends string>(
  id: T,
  params: { properties: S[] }
): {
  id: T;
  properties: {
    [K in S]: string;
  };
} {
  return {} as any;
}

// type is { id: 0; properties: { "hi": string; "you": string; } }
const u = getContact(0, { properties: ["hi", "you"] });