I currently have a setup with various interfaces and objects as outlined below:
interface ServicesList {
[key: string]: Service;
}
interface Service {
uuid: string;
characteristics: CharacteristictList;
}
interface CharacteristictList {
[key: string]: string;
}
const ServiceAndCharacteristicMap: ServicesList = {
firstService: {
uuid: '0x100',
characteristics: {
characteristicOne: '0x0101',
},
},
secondService: {
uuid: '0x200',
characteristics: {
secondCharacteristic: '0x0201'
}
}
};
Following that, I have implemented the following function:
function sendCharacteristic<T extends Service, K extends keyof T['characteristics']>(props: {
service: T;
characteristic: K;
}) {
console.log(props.service.uuid,
props.service.characteristics[props.characteristic])
}
The current issue I am facing is TypeScript's compile-time error message stating:
Type 'K' cannot be used to index type 'CharacteristictList'
My objective here is to restrict the second parameter (characteristic
) for enhanced type safety when selecting keys. For instance, the following usage should be valid:
//should succeed
sendCharacteristic({
service: ServiceAndCharacteristicMap.firstService,
characteristic: 'characteristicOne'
});
However, this attempt should fail because characteristicOne
is associated with firstService
, not secondService
:
//should fail since characteristicOne belongs to firstService
sendCharacteristic({
service: ServiceAndCharacteristicMap.secondService,
characteristic: 'characteristicOne'
});
As of now, neither of these invocations of sendCharacteristic
trigger any compilation errors.
What would be the correct approach to constrain the characteristic
parameter to ensure type safety based on the specific instance of Service
being passed in?