Home:ALL Converter>Typescript enforce alias type in argument

Typescript enforce alias type in argument

Ask Time:2020-06-05T15:43:11         Author:Marv

Json Formatter

I am currently having an issue with type unions/aliases. I have an alias for values which might be null or undefined and a function that handles these values.

This works fine and everything is safe. No there are situation where through oversights or whatever, a safe value, which can't be null or undefined is passed to the function. This does not break anything, because the function expects safe values aswell, but Typescript does not complain.

The code looks something like this:

type Maybe<T> = T | null | undefined;

function handleDangerousValue<T>(val: Maybe<T>): T {
    // Check stuff
    return val as unknown as T;
}

const safeValue: number = 1;
const unsafeValue: Maybe<number> = null;

// Would like a type error here
handleDangerousValue(safeValue);

// This is fine
handleDangerousValue(unsafeValue);

I would like to somehow have Typescript tell me that safeValue does not have the correct type.

I know that this does not work because of how the union type is defined, but I do not know any solution on how to enforce this. This would probably be solvable by having DangerousValue<T> become a class, but I would prefer it as a type, as I do not want extra boilerplate to solve a typing problem.

edit:

I tinkered a bit more and got some progress:

type Maybe<T> = T | null | undefined;
type EnforceMaybe<T> = Maybe<T> extends T ? Maybe<T> : never;

function handleDangerousValue<T>(val: EnforceMaybe<T>): T {
    // Check stuff
    return val as unknown as T;
}

const safeValue: number = 1;
const unsafeValue: Maybe<number> = null as Maybe<number>;

// Correctly finds issue
const n1: number = handleDangerousValue(safeValue);

// Now thinks that the return type should be a Maybe
const n2: number = handleDangerousValue(unsafeValue);

Now the values that can't be null are not allowed, but typescript is not able to infer the inner type of the Maybe anymore.

Can I somehow infer that for the return type?

Author:Marv,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62210442/typescript-enforce-alias-type-in-argument
yy