I created a custom method using the RXJS library which looks like this :
function Subject<T>(t: T):T {
return t;
}
In addition, I defined an interface that specifies the structure of my application values. Additional keys can be added to this interface.
interface IState {
key1: number;
key2: string;
}
Lastly, I have a Store
object that conforms to the IState
interface by utilizing the generic function wrapper (which serves as an alias for the RXJS
subject).
let Store : IState= Subject<IState>({
key1: void 0,
key2: void 0,
})
Let's now implement two methods for getting and setting values in the store:
Setting a value in the store:
function set<T>(name: keyof IState, statePart: T) {
Store={
...Store,
[name]: statePart
};
Usage example: set<string>("key1", "3");
This function allows us to use only valid keys that belong to the IState
interface without any errors.
However, when we look at the Select
method:
(the correct call should be in this format: )
let myVal:number = select<number>("key1");
Here is the implementation of the Select
method:
function select<T>(k: keyof IState): T {
return <T>Store[k]; // <-- error here
}
The error message states that 'string | number' cannot be converted to type 'T'. The Type 'number' is not comparable to type 'T'.
Question:
Why is this happening? If I remove the keyof
keyword:
function select<T>(k): T {
return <T>Store[k];
}
The code compiles without issues, but it doesn't seem logical since Store
is defined as type Istate
which contains the keys specified in Istate
.
How can I make the select
method enforce selection of only keys from Istate
?