Home > Enterprise >  Typescript type not narrowed in generic function
Typescript type not narrowed in generic function

Time:02-01

Take for example the following types.

type ZoneAndTools = {
    a: number,
    b: string,
    c: object,
}

type ZoneTypes = keyof ZoneAndTools;

Applied to this function, I'm looking for to extract the type from a map

function transform<T extends ZoneTypes>(
    map: Map<T, ZoneAndTools[T]>,
    key: T
): ZoneAndTools[T] | undefined {
    return map.get(key);
}

And here is a use case :

const a: Map<ZoneTypes, ZoneAndTools[ZoneTypes]> = new Map();
const b = transform(a, 'a');
// b is string | number | object | undefined instead of number | undefined

My question to the experts, why doesn't the transform function in this use case return number> | undefined ?

Playground

CodePudding user response:

I guess it is because you give the map type ZoneTypes, which could be any of those.

const a: Map<ZoneTypes, ZoneAndTools["a"]> = new Map();

You should strictly type it, as you already know the ZoneAndTools is type of a

const a: Map<"a", ZoneAndTools["a"]> = new Map();

You could also type this furher and create custom Map for ZoneAndTools

type ZoneAndTools = {
  a: number;
  b: string;
  c: object;
};

type ZoneTypes = keyof ZoneAndTools;

function transform<T extends ZoneTypes>(
  map: Map<T, ZoneAndTools[T]>,
  key: T
): ZoneAndTools[T] | undefined {
  return map.get(key);
}

type ZoneMap<T extends ZoneTypes> = Map<T, ZoneAndTools[T]>

const a: ZoneMap<"a"> = new Map();
const b = transform(a, "a");
  •  Tags:  
  • Related