如何通过前一个参数的值推断函数参数的类型?
How to deduce the type of function argument by value of previous argument?
使用打字稿,我希望 compiler/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 定义为名称和用户类型的联合,即 string | number
,但它不依赖于实际传递给函数的键。要使键和值依赖,您需要在函数中使用泛型,如下所示:
function run<T extends keyof AuxType>(key: T, value: AuxType[T]) {
return dostuff(key, value)
}
现在键必须是 AuxType 的键(这就是 extends
所做的)并且值必须是 AuxType 中该键的对应类型。
使用打字稿,我希望 compiler/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 定义为名称和用户类型的联合,即 string | number
,但它不依赖于实际传递给函数的键。要使键和值依赖,您需要在函数中使用泛型,如下所示:
function run<T extends keyof AuxType>(key: T, value: AuxType[T]) {
return dostuff(key, value)
}
现在键必须是 AuxType 的键(这就是 extends
所做的)并且值必须是 AuxType 中该键的对应类型。