Julian W.
Julian W.

Reputation: 1571

How to use a type in a union as Type Alias

I have a type definition error - Type 'RowProp<RowType>' is not assignable to type 'RowProp<number>'. with the following code.

export type RowType = number | string;

export interface RowProp<T> {
  id: string;
  row: T;
}

export interface TableData {
  id: string;
  template?: (e: RowProp<RowType>) => JSX.Element;
}

const templateA = (e: RowProp<number>) => <div></div>;

const data: TableData = {
  id: '1',
  template: templateA
}

How can I fix this issue.

Upvotes: 0

Views: 122

Answers (1)

user10064387
user10064387

Reputation:

I'm not sure what you're trying to accomplish, but you might be looking for generics:

export interface TableData<T extends RowType> {
    id: string;
    template?: (e: RowProp<T>) => JSX.Element;
}

const data: TableData<number> = {
    id: '1',
    template: templateA
}

The above passes strict compilation. By allowing TableData to accept a generic type parameter T, we can now specify what the template's RowProp will contain.

That said, Heretic Monkey's comment above also solves the issue.

Upvotes: 1

Related Questions