2

I have a generic component class that I want to use within another component. Is there a way to specify the type of the generic?

Example

class GenericComponent<T> extends React.Component<{
    value: T;
    update: T => void;
}, any> {
    ...
}

class AnotherComponent extends React.Component<any, any> {
    render() {
        let foobar: 'foo | 'bar';
        return <View>
            <GenericComponent
                value={'foo'}  // Type of T is inferred as 'string' instead of '"foo" | "bar"'
                update={value => foobar = value} // Type 'string' is not assignable to type '"foo" | "bar"'
            />
        </View>
    }
}

I know I could use value={'foo' as 'foo' | 'bar'}, but is there a cleaner way?

Something like <GenericComponent<'foo' | 'bar'> /> or <GenericComponent/> as GenericComponent<'foo' | 'bar'>.

Matthew Jensen
  • 132
  • 1
  • 5

0 Answers0