sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.04k stars 532 forks source link

`type ExtendsFrom<Type, Subtype extends Parent> = Subtype;` #473

Open AlabasterAxe opened 1 year ago

AlabasterAxe commented 1 year ago

I'm assuming I'm missing something because this feels like a basic type but I haven't figured out how I can replicate this functionality with the built in Utility types or any of the types in typefest.

It's basically just a type intersection with better error reporting.

A couple of examples of when this could be useful:


// Type-safe string union subset
type AllowedValues = 'foo' | 'bar' | 'baz';

// we get eager type errors if one of the values specified in
// this string union does not appear in AllowedValues.
type RestrictedAllowedValues = ExtendsFrom<AllowedValues, 'foo' | 'bar'> 

// Constraining config value types
type ConfigKeys = 'blah' | 'blah2';

type AllowedValue = string | boolean | number;

type BaseConfig = {
    [key in ConfigKeys]: AllowedValue
}

type Config = ExtendsFrom<BaseConfig, {
    blah: string,
    blah2: boolean,
}>

Upvote & Fund

Fund with Polar

AlabasterAxe commented 1 year ago

@marcello3d FYI