#dynamic type based on object array

16 messages · Page 1 of 1 (latest)

marsh thunder
#

Is it possible to have a dynamic type that pulls from a property in an array of objects?
Basically this:

const obj = [
    { name: 'test1' },
    { name: 'test2' },
    { name: 'test3' },
    ...
];

into

type Test = 'test1' | 'test2' | 'test3' | ...;

Thankyou 🙂

deep wren
#

You can do this way:

const obj = [
    { name: 'test1' },
    { name: 'test2' },
    { name: 'test3' },
] as const;

type Test = (typeof obj)[number]['name'];
icy gustBOT
#
const obj = [
    { name: 'test1' },
    { name: 'test2' },
    { name: 'test3' },
] as const

type Obj = typeof obj
type Name = Obj[number]['name']
//   ^? - type Name = "test1" | "test2" | "test3"
brave trellis
#

Yep.

#

For more information see:

#

!hb indexed access

icy gustBOT
marsh thunder
#

im not sure var const will work im my situation

#
export type HonoPassportStrategy<TUser> = {
    name: string;
    authenticate: (ctx: Context) => Promise<TUser> | TUser;
};

export type HonoPassportOptions<TUser, TSessionUser> = {
    strategies: HonoPassportStrategy<TUser>[];
    serializeUser?: (user: TUser) => TSessionUser | Promise<TSessionUser>;
    deserializeUser?: (user: TSessionUser) => TUser | Promise<TUser>;
};

export type HonoPassportReturn<TUser, TSessionUser> = {
    initialize: () => MiddlewareHandler<HonoPassportEnv<TUser, TSessionUser>>;
    login: (
        strategyName: string,
    ) => MiddlewareHandler<HonoPassportEnv<TUser, TSessionUser>>;
    logout: () => MiddlewareHandler<HonoPassportEnv<TUser, TSessionUser>>;
};

this might provide some more info

#

can i restrict strategyName: string to the name's from the strategies array

brave trellis
#

Not unless you specify what names are allowed.

marsh thunder
#

ye that is user side config stuff

brave trellis
#

Sure, types are for compile time checks

#

If you don't know what users are going to use at compile time, then you can only resort to runtime checks.

marsh thunder
#

yup which i already got in place

#

no worries, thankyou very much for your time 🙂