typescript键入是否可以确保函数将返回请求的键?

typescript键入是否可以确保函数将返回请求的键?,typescript,Typescript,一些web服务根据请求的属性提供内容。我想创建一个函数,该函数接受属性,在内部调用web服务并返回请求的数据 使用数据的函数现在应该知道特定键现在不是未定义的 在自己寻找解决方案时,我发现了一些可能有用的东西,但我无法从中创造出有用的东西: 还有一个额外的麻烦:在这种情况下,默认属性总是像id一样存在 接口{ id:字符串; foo?:字符串; 条?:编号; } //在这里以某种方式使用“keyof Something”? 键入OptionalProp='foo'|'bar' 键入s

一些web服务根据请求的属性提供内容。我想创建一个函数,该函数接受属性,在内部调用web服务并返回请求的数据

使用数据的函数现在应该知道特定键现在不是未定义的

在自己寻找解决方案时,我发现了一些可能有用的东西,但我无法从中创造出有用的东西:

还有一个额外的麻烦:在这种情况下,默认属性总是像id一样存在

接口{
id:字符串;
foo?:字符串;
条?:编号;
}
//在这里以某种方式使用“keyof Something”?
键入OptionalProp='foo'|'bar'
键入somethingspective={
[k in k]:不可为空
};
函数get(属性:OptionalProp[]):Something{
常量结果:某物={
身份证号码:1337
};
if(properties.includes('foo')){
result.foo='bar';
}
if(properties.includes('bar')){
result.bar=42;
}
返回结果;
}
log(用法());
函数用法():编号{
const result=get(['bar']);
返回result.bar*1;
}
因此,需要确定某一类型的键是可选的,您还可以为
get()
函数提供一个调用签名,该函数承诺返回一个
Something
,现在需要一些以前可选的属性(最好将其设置为一个函数,以便实现签名可以像以前一样松散;否则在实现过程中会收到很多投诉)。还请注意,在标准库中调用了一个类型别名,该别名接受对象类型
T
,并返回一个新类型,其中现在需要所有可选属性。使用
required
Pick
的组合,应该可以:

interface Something {
  id: string;
  foo?: string;
  bar?: number;
}

// get the optional keys of an object type
type OptionalKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? K : never }[keyof T];

type OptionalProp = OptionalKeys<Something>

// make get() a generic function that returns an intersection of Something with
//  a Required<Pick<Something, K>> for the passed-in K parameters

function get<K extends OptionalProp>(
  properties: K[]
): Required<Pick<Something, K>> & Something;
function get(properties: OptionalProp[]): Something {
  // impl here
  return null!
}

const result = get(['bar']);
// const result: Required<Pick<Something, "bar">> & Something
result.bar * 1; // okay now

好的,希望能有帮助。祝你好运!

你有什么问题?
function get<K extends OptionalProp,
  R extends Something=Required<Pick<Something, K>> & Something
>(properties: K[]): { [P in keyof R]: R[P] };
function get(properties: OptionalProp[]): Something { /* impl */ }
  // impl here
  return null!
}

const result = get(['bar']);
//const result: {
//    bar: number;
//    id: string;
//    foo?: string | undefined;
//}