Please see the following example code:
type TestKey = 'a' | 'b' | 'c';
function printTestValue(key: TestKey, value: string) {
console.log(key, value);
}
{
// case 1
const testValues: { [key: TestKey]: string } = { // TS1337 on key
a: 'A',
b: 'B',
c: 'C',
};
for (const key in testValues)
if (Object.hasOwn(testValues, key))
printTestValue(key, testValues[key]); // TS2345 on key, TS7053 in testValues[key]
}
{
// case 2
const testValues: { [key in TestKey]: string } = {
a: 'A',
b: 'B',
c: 'C',
};
for (const key in testValues)
if (Object.hasOwn(testValues, key))
printTestValue(key, testValues[key]); // TS2345 on key, TS7053 in testValues[key]
}
{
// case 3, trying to remove key 'c'
const testValues: { [key in TestKey]: string } = { // TS2741 on testValues
a: 'A',
b: 'B',
};
for (const key in testValues)
if (Object.hasOwn(testValues, key))
printTestValue(key, testValues[key]); // TS2345 on key, TS7053 in testValues[key]
}
{
// case 4
const testValues: { [key in TestKey]?: string } = {
a: 'A',
b: 'B',
};
for (const key in testValues)
if (Object.hasOwn(testValues, key))
printTestValue(key, testValues[key]); // TS2345 on key, TS7053 in testValues[key]
}
Here, what I'm trying to accomplish is as follows:
- restrict the value of 'key' argument of
printTestValue()function. - restrict the value of the keys of the
testValuesobject, so that it's key-value pair can be safely used forprintTestValue()function, while it does not have to have all the keys specified inTestKeytype.
But each trial (denoted as case 1, 2, 3, 4) has error(s) (shown in comments). How can I implement an error-free version?