#Loosening type with generic `extends`

6 messages · Page 1 of 1 (latest)

desert zinc
#

With function foo<T>(value: T), the inferred type is loosen 123 -> number, but as soon as I have function foo<T extends string | number>(value: T), it's got narrowed 123 -> 123. I would expect it to keep the same behavior unless using const T. Is there a way to use extends while keeping loosening type?

Edit: playground https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMMBBAPAFQHwAoBuAhgDYgCmAXIpgJRWYDaAuogN4BQiXiATmVCB5IGRUmSYBudgF927APTzEhKmBABbAEZkezdhAQBnKMsQBeZGlwBGAEwBmGlPahIsBJYBCWRGQAeUGRgACaGiMY8MGAA5ogAPohqWjp4ouT0dNTMbJzcfAJCiCIk5JIycoq+fgAOZNCIUHCI0fyJGtq6LFHGZITBiHDAiHb2egZgxoia5l42Dk7sQA

high gull
#

@desert zinc This behavior predates the const keyword (edit: as a modifier on type params) - when a type is specifically constrainted to a primitive type, TS will try to infer a specific value.

#

There may be a trick to avoid that while still constraining the subtype, but I'm not aware of one personally.

#

You could write this as an overload signature:

#
function fnB(value: string): string[];
function fnB(value: number): number[];
function fnB(value: string | number) {
    return [value];
}
desert zinc