I'd like to say that I'm at beginner's level in both Typescript and Angular (including ngrx).
I'm trying to wrap my head around how the select method of the Store class can accept a string literal as a parameter. Here's code:
export interface AppState {
readonly tutorial: Tutorial[];
}
export class ReadComponent {
constructor(private store: Store<AppState>) {
this.tutorials = store.select('tutorial');
}
}
Now, I see the the AppState class has a tutorial property, and that seems to be what the call store.select('tutorial') is going for, but how though? How is it that if I change the literal being passed to select ex. store.select('yadayada'), the compiler issues an error Argument of type '"yadayada"' is not assignable to parameter of type '"tutorial"'. How are "tutorial" and "yadayada" types? Why is the compiler taking a string literal as a type?
It infers it as a key on the store object type and can infer the value type from that. For a example you can define a generic function:
const getKey = <T>(obj: T, key: keyof T) => obj[key] ;
It will correctly infer the return type and give a compiler error if key is not a key of T. You can explicitly type the return value of the function as T[keyof T]. Typescript generics and type inference is insanely powerful.