最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Mapped generic array type missing properties - Stack Overflow

programmeradmin7浏览0评论

I'm trying to create a GenericTable class that has a property based on the generic type that I'm giving it.

Currently I have this:

interface ITableColumn<C> {
    name: string;
    isUnsortable?: boolean;
    sortAdapter?: (a: C, b: C) => number;
    template?: TemplateRef<{ $implicit: C }>;
    width?: number;
}

//Map array of types to ITableColumn[] of the same types
type MapToColumns<
    T extends unknown[],
    Acc extends readonly ITableColumn<unknown>[] = [],
> = T['length'] extends Acc['length'] ? Acc : MapToColumns<T, readonly [...Acc, ITableColumn<T[Acc['length']]>]>;

class GenericTable<T extends unknown[]> {
    public constructor(private _columns: MapToColumns<T>) {
        const index = _columns.findIndex(() => ...)
    }
}

My issue is that 'findIndex' doesn't exists anymore on the _columns property. All works fine when I'm not using a generic but eg: [string, number, string] instead. Anyone see what is going wrong here, or know of any better approaches?

I'm trying to create a GenericTable class that has a property based on the generic type that I'm giving it.

Currently I have this:

interface ITableColumn<C> {
    name: string;
    isUnsortable?: boolean;
    sortAdapter?: (a: C, b: C) => number;
    template?: TemplateRef<{ $implicit: C }>;
    width?: number;
}

//Map array of types to ITableColumn[] of the same types
type MapToColumns<
    T extends unknown[],
    Acc extends readonly ITableColumn<unknown>[] = [],
> = T['length'] extends Acc['length'] ? Acc : MapToColumns<T, readonly [...Acc, ITableColumn<T[Acc['length']]>]>;

class GenericTable<T extends unknown[]> {
    public constructor(private _columns: MapToColumns<T>) {
        const index = _columns.findIndex(() => ...)
    }
}

My issue is that 'findIndex' doesn't exists anymore on the _columns property. All works fine when I'm not using a generic but eg: [string, number, string] instead. Anyone see what is going wrong here, or know of any better approaches?

Share Improve this question edited Mar 22 at 12:11 DrawMen asked Mar 22 at 11:49 DrawMenDrawMen 408 bronze badges 2
  • could you provide the full code with ITableColumn? – Alexander Nenashev Commented Mar 22 at 12:08
  • yes, I have added it to my code sample – DrawMen Commented Mar 22 at 12:11
Add a comment  | 

1 Answer 1

Reset to default 2

Why just not to map by the index?:

The related documentation

Playground

type MapToColumns<T extends unknown[]> = {[I in keyof T]: ITableColumn<T[I]>};
发布评论

评论列表(0)

  1. 暂无评论