#Getting a type of another field within the same interface

28 messages · Page 1 of 1 (latest)

dusky scroll
#

Hey, how can i set the type from sourceKey field to the type of cell parameter?

So that if sourceKey is type of number then the cell parameter of renderCell function is 100% a number.

export interface ColumnDef<TDataType> {
    id?: string;
    sourceKey: keyof TDataType;
    header: string | (() => string);
    sortable?: boolean;
    renderCell?: (cell: Cell<TDataType>) => any;
}
graceful mirage
#

keyof TDataType would be number if it's an array though

#

do you mean like, TDataType[sourceKey] being a number?

#

if you change the arity you could do```ts
export interface ColumnDef<SourceKey extends string, TDataType extends Record<SourceKey, number>> {
id?: string;
sourceKey: SourceKey;
header: string | (() => string);
sortable?: boolean;
renderCell?: (cell: Cell<TDataType>) => any;
}

dusky scroll
graceful mirage
#

otherwise you could probably do something like this

sourceKey: { [K in TDataType as TDataType[K] extends number ? K : never]: K }[keyof TDataType];
```or```ts
sourceKey: { [K in TDataType]: TDataType[K] extends number ? K : never }[keyof TDataType];
```or```ts
sourceKey: keyof { [K in TDataType as TDataType[K] extends number ? K : never]: unknown /* doesn't matter */ };
```with everything else being the same
graceful mirage
#

i see nothing relating to number there.

dusky scroll
#

number was just an example

#

it could be

type TDataType = "updated_at" | "session" | number
graceful mirage
#

ohhhh i misread

#

one sec

#

i shouldn't be having multiple convos at once lol

dusky scroll
#

and then the inner type for Cell should be the type assigned to sourceKey

graceful mirage
#

don't know how i misread that badly, mb

dusky scroll
#

Nah, i probably explained it poorly

graceful mirage
#

i don't think you can do this with an interface, seems like you're looking for a DU which would be achieved with a distributive conditional here

dusky scroll
#

Im open for any solution, doesnt have to be an interface 😄

graceful mirage
#
export type ColumnDef<T> = T extends T ? {
    id?: string;
    sourceKey: T;
    header: string | (() => string);
    sortable?: boolean;
    renderCell?: (cell: Cell<T>) => any;
} : never
#

the T extends T is a tautology, T extends unknown or (less commonly) T extends any would also work
just needs a conditional that will always pass with T on the left, so it can distribute:

#

!hb distrib

clear shellBOT
dusky scroll
graceful mirage
#

keyof "updated_at" or keyof number don't really make sense for that i don't think

dusky scroll
#

okay it works, i just needed to pass the keyof inside the type

readonly columns: ColumnDef<keyof TDataType>[];
#

thanks pepechristmas

civic root