#Typing issue

14 messages · Page 1 of 1 (latest)

late nimbus
#

I have the following code:

const EOption = {
    Some: 0,
    None: 1
} as const;

interface Enum<T> {
    variant: T[keyof T]
}

class Option<T> implements Enum<typeof EOption> {
    variant = EOption.Some;
}

type ExtractEnumType<T> = T extends Enum<infer R> ? R : never;

type L = ExtractEnumType<Option<string>>

What I'm expecting is that L would be of type "typeof EOption" but it seems to be "never", How can I make it so that is the case?

north umbra
#

@late nimbus ExtractEnumType tries to extract the type of Enum
but in your L case you are passing an Option
are you sure about that?

late nimbus
plain scaffold
#

@late nimbus Option<string> is { variant: 0 }

#

The information about Enum isn't present in the type, it was only a constraint checked when creating Option.

rose glacierBOT
#
type Expand<T> = {
  [K in keyof T]: T[K];
} & {};

const EOption = {
    Some: 0,
    None: 1
} as const;

interface Enum<T> {
    variant: T[keyof T]
}

class _Option<T> implements Enum<typeof EOption> {
    variant = EOption.Some;
}

type ExtractEnumType<T> = T extends Enum<infer R> ? R : never;


type T = Expand<_Option<string>>
//   ^? - type T = {
//       variant: 0;
//   }

type L = ExtractEnumType<T>
late nimbus
plain scaffold
#

Well, your L contains a value of T from Enum<T>. If a value is 0, you can't derive from that value what T it came from

#

If Option contains T, then maybe you can get it

rose glacierBOT
#
type Expand<T> = {
  [K in keyof T]: T[K];
} & {};

const EOption = {
    Some: 0,
    None: 1
} as const;

interface Enum<T> {
    variant: T[keyof T]
}

class _Option<T> implements Enum<typeof EOption> {
    t!: typeof EOption
    variant = EOption.Some;
}

type ExtractEnumType<T> = T extends { t: infer R } ? R : never;

type T = Expand<_Option<string>>
//   ^? - type T = {
//       t: typeof EOption;
//       variant: 0;
//   }

type L = ExtractEnumType<T>
//   ^? - type L = {
//       readonly Some: 0;
//       readonly None: 1;
//   }
plain scaffold
#

This isn't the type of pattern I've ever used. So you want just want to think about whether there is another way to do what you want to do.

late nimbus
#

oh, i didn't even think about doing that! Thanks a bunch

#

I think this is just what I'm looking for

plain scaffold
#

Oki