Identity Functions 5 exercises
Problem

Specifying Where Inference Should Not Happen

Here we're building a makeFiniteStateMachine function where state is a string as seen by TState extends string:


export const makeFiniteStateMachine = <TState extends string>(
config: FSMConfig<TState>
) => config;

We then put it into an FSMConfig interface, which looks

Loading exercise

Transcript

00:00 In this exercise, we have an interesting problem. We have a makeFiniteStateMachine function. This makeFiniteStateMachine takes in a config of fsmConfig, and one of the type parameters, or the only type parameter we're using is tstate. Now, tstate can be inferred in one of two places. It can be inferred in this initial slot,

00:18 which is the initial state that we're going to be in. So for instance, we have initial A here, and then states down here should be A or B. So in theory, when we call this function, makeFiniteStateMachine, it should be inferring A or B in the type parameter, but it's not. It's just inferring A here. This is pretty gross.

00:38 If we look at another one down here, then actually we have states A and B, and we have an initial of C, and we're expecting C not to be allowed because it's not one of A or B here. So if we take a look, it's actually just being inferred as C. So what we want to do is inside this ts or fsmConfig here,

00:57 we want to say, okay, this initial, we don't want you to infer from it, TypeScript. We basically want it to not infer if possible. And there is a little type at the top here called noinfer. Your job is to work out how to solve this problem when inside this fsmConfig, that's all we need to change,

01:15 using this type of noinfer. Good luck.