My custom types and interfaces are as follows:
export type MultiMedia = 'image' | 'audio' | 'video';
export type FieldType = 'string' | 'number' | 'boolean' | MultiMedia;
export interface Field {
name: string,
label: string,
type: FieldType,
validator: <T>(val: T) => boolean,
bounds: { lower: number; upper: number }
}
export interface Theme {
title: string,
logoPath: string,
tags: string[],
fields: Field[]
}
The field type varies between different objects, so I defined a generic method validator
in the Field
interface. However, TypeScript raises an error when creating an object literal that implements the Field
interface.
Type '(val: string) => boolean' is not assignable to type '(val: T) => boolean.
const fields: Field[] = [
{
name: "firstName",
label: "First Name",
type: "string",
bounds: { lower: 1, upper: 1 },
validator: (val: string) => {
return val.length > 20;
}
}
To resolve the issue, I modified the Field
interface as shown below.
export interface Field<T> {
name: string,
label: string,
type: FieldType,
validator: (val: T) => boolean,
bounds: { lower: number; upper: number }
}
However, TypeScript now complains about the fields
property in the Theme
interface.
Generic Type 'Field' requires 1 type argument(s).