TypeScript second parameter type based on first parameter type
You want to use function overloads to get the type checking working properly:
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 {}
}
or simpler, just use strings:
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'.
And of course you don't have to list the literal strings in the overloads, you can group similar ones into a type definition:
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 {}
}