我有第一个参数可能值的枚举,我希望第二个参数基于第一个参数。因此,如果给出 NAME,我希望第二个参数为字符串。如果给出 AGE,我希望第二个参数是一个数字。
我怎样才能做这样的事情?
enum KeyType {
NAME,
AGE
}
class MyClass {
public static setProperty(key: KeyType.NAME, value: string): void { }
public static setProperty(key: KeyType.AGE, value: number): void { }
}
我想这样调用方法:
MyClass.setProperty(KeyType.NAME, 'John');
此外,这应该显示错误:
MyClass.setProperty(KeyType.NAME, 5);
//5 不是字符串
在这个例子中它不起作用,因为 key
类型定义错误(键类型实际上是枚举的值,所以键类型是 0
)。
我也乐于接受有关使用仅允许特定类型用于特定参数键的功能的不同方法的建议。
最佳答案
您想使用函数重载来使类型检查正常工作:
enum KeyType {
NAME,
AGE
}
class MyClass {
public static setProperty(key: KeyType.NAME, value: string): void;
public static setProperty(key: KeyType.AGE, value: number): void;
public static setProperty(key: KeyType, value: (string | number)): void {}
}
或者更简单,只使用字符串:
class MyClass {
public static setProperty(key: 'name', value: string): void;
public static setProperty(key: 'age', value: number): void;
public static setProperty(key: string, value: (string | number)): void {}
}
MyClass.setProperty('name', 42); // Argument of type '"name"' is not assignable to parameter of type '"age"'.
MyClass.setProperty('age', 42); // Ok
MyClass.setProperty('name', 'foo'); // Ok
MyClass.setProperty('age', 'foo'); // Argument of type '"foo"' is not assignable to parameter of type 'number'.
当然你不必在重载中列出文字字符串,你可以将相似的分组到一个类型定义中:
type StringProperty = 'name' | 'address';
type NumberProperty = 'age' | 'salary';
class MyClass {
public static setProperty(key: StringProperty, value: string): void;
public static setProperty(key: NumberProperty, value: number): void;
public static setProperty(key: string, value: (string | number)): void {}
}
关于javascript - TypeScript 第二个参数类型基于第一个参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47092523/