Skip to content

Instantly share code, notes, and snippets.

@solidsnack
Last active May 15, 2019 19:05
Show Gist options
  • Save solidsnack/f3e63e7730b43ce3a2267ecb96d025c9 to your computer and use it in GitHub Desktop.
Save solidsnack/f3e63e7730b43ce3a2267ecb96d025c9 to your computer and use it in GitHub Desktop.
export default function null2undefined<T, K extends keyof T>(
o: T,
name: K,
): NullableAsUndefined<T>[K] {
const val = o[name];
return val || undefined; // Error on this line --
// Type 'T[K] | undefined' is not assignable to
// type 'T[K] extends infer U | null ? U | undefined : T[K]'.
// Type 'undefined' is not assignable to
// type 'T[K] extends infer U | null ? U | undefined : T[K]'.
}
type NullableAsUndefined<T> = {
[K in keyof T]: T[K] extends (infer U | null) ? U | undefined : T[K]
};
// Similar concept:
function defaultingGeneric<T>(x: T): NonNullable<T> | undefined {
return x || undefined; // Error on this line --
// Type 'T | undefined' is not assignable to
// type 'NonNullable<T> | undefined'.
// Type 'T' is not assignable to
// type 'NonNullable<T> | undefined'.
// Type 'T' is not assignable to
// type 'NonNullable<T>'.
}
// No error on this one:
function defaultingString(x: string | null): NonNullable<typeof x> | undefined {
return x || undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment