[英]How to pass arguments to function as then()'s argument in Promise chain with previous resolved value being kept?
[英]How to deduce the type of function argument by value of previous argument?
使用打字稿,我希望编译器/IDE 能够推断出参数的类型。 我如何使它工作? 我的函数的第一个参数是一个字符串,它的值将决定可以作为第二个参数传递的数据类型。 但我不能那样做。 我正在分享我期望编译器在这种情况下如何工作,但它对我没有帮助。
interface AuxType { name: string, user: number } type ValueType = AuxType[keyof AuxType] function run(key: string, value: ValueType) { return dostuff(key, value) } run('name', "Stack") // Works as expected run('user', 2) // Works as expected run('name', 2) // Expecting this to error but it is not run('user', "Stack") // Expect this to error but it works in typescript
甚至可以在打字稿中使用吗? 对于第一个参数的字符串文字值,这不应该是可能的吗?
您需要使用泛型。 现在,您只是将 ValueType 定义为 name 和 user 类型的联合,即string | number
string | number
,但它不依赖于实际传递给函数的键。 要使键和值依赖,您需要在函数中使用泛型,如下所示:
function run<T extends keyof AuxType>(key: T, value: AuxType[T]) {
return dostuff(key, value)
}
现在键必须是 AuxType 的键(这就是extends
所做的),值必须是 AuxType 中该键的对应类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.