我在typescript Playground中有一个演示
const C = {
METHOD: {
'1': 2,
'2': 2,
'3': 3
},
CCSIGNFLAG: {
'4': 4,
'5': 5,
'6': 6
}
};
interface IKey {
method: '123123123';
ccSignFlag: '2222';
[key: string]: string;
}
interface Ivalue {
method: '1' | '2' | '3';
ccSignFlag: '4' | '5' | '6';
[key: string]: string;
}
function test<T extends keyof IKey>(field: T, value: Ivalue[T]) {
switch (field) {
case 'method':
return C['METHOD'][value];
}
}
test('ccSignFlag', '4');显示错误:Type 'Ivalue[T]' cannot be used to index type '{ '1': number; '2': number; '3': number; }'
我希望第一个参数约束第二个参数的输入
我该怎么办?
发布于 2020-01-20 22:49:06
我找到了a solution,但我不认为这是最好的解决方案,还有其他方法吗?
const C = {
METHOD: {
'1': 2,
'2': 2,
'3': 3
},
CCSIGNFLAG: {
'4': 4,
'5': 5,
'6': 6
}
};
interface IKey {
method: '123123123';
ccSignFlag: '2222';
[key: string]: string;
}
interface Ivalue {
method: '1' | '2' | '3';
ccSignFlag: '4' | '5' | '6';
[key: string]: string;
}
function test<T extends keyof IKey>(field: T, value: Ivalue[T]) {
switch (field) {
case 'method':
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
return C['METHOD'][value as keyof typeof C['METHOD']];
case 'ccSignFlag':
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
return C['CCSIGNFLAG'][value as keyof typeof C['CCSIGNFLAG']]
default:
return value;
}
}
test('ccSignFlag', '4');https://stackoverflow.com/questions/59781115
复制相似问题