【发布时间】:2019-03-13 23:09:10
【问题描述】:
一些 Web 服务根据请求的属性提供内容。我想创建一个函数来获取属性,在内部调用 Web 服务并返回请求的数据。
使用数据的函数现在应该知道特定键现在不是未定义的。
在自己寻找解决方案时,我发现了一些可能有帮助的东西,但我无法从中创造出有用的东西:
- NonNullable
- Pick
- Is it possible to extract keys from a parameter for type inference in Typescript?
- Typescript: constrain argument of function to be a key of an object associated with a value of a particular type
还有一些额外的麻烦:在这种情况下,总是有一些默认属性,比如 id。
interface Something {
id: string;
foo?: string;
bar?: number;
}
// use 'keyof Something' in some ways here?
type OptionalProp = 'foo' | 'bar'
type SomethingSpecific<K extends keyof Something> = {
[k in K]: NonNullable<Something[k]>
};
function get(properties: OptionalProp[]): Something {
const result: Something = {
id: '1337'
};
if (properties.includes('foo')) {
result.foo = 'bar';
}
if (properties.includes('bar')) {
result.bar = 42;
}
return result;
}
console.log(usage());
function usage(): number {
const result = get(['bar']);
return result.bar * 1;
}
【问题讨论】:
-
你有什么问题?
标签: typescript