I have such a year
import React,{InputHTMLAttributes} from "react";
export interface faceTegInput extends InputHTMLAttributes<HTMLInputElement> {
readonly Tag: string;
readonly key: string;
}
export const inputSetSearch: faceTegInput = {
type: "text",
size: 50,
maxLength: 150,
placeholder: "Search for anything",
alt: "search",
spellCheck: false,
autoComplete: "off"
};
I get this error
Type '{ type: string; size: number; maxLength: number; placeholder: string; alt: string; spellCheck: false; autoComplete: string; }' is missing the following properties from type 'faceTegInput': Tag, key.
What is the reason I can not understand.?
You are not providing Tag and key in inputSetSearch. You should whether add them to the inputSetSearch or make them optional.
DEMO
Related
I'm working with React and Typescript. I'm getting the following error in my terminal and it's not clear what I'm doing wrong.
TS2322: Type '{ question: number; label: string; prop: string; type: string; style: string; placeholder?: string; options?: any; }' is not assignable to type '{ question: any; label: any; prop: any; style: any; type: any; options: any; }'.
Property 'options' is optional in type '{ question: number; label: string; prop: string; type: string; style: string; placeholder?: string; options?: any; }' but required in type '{ question: any; label: any; prop: any; style: any; type: any; options: any; }'.
Below is the relevant code. Notice I got this error before I used an interface as well as after creating one. The error is happening with my Dropdown component inside of the formGroup component below. What am I doing wrong?
// formGroup Component
const myForm: Form = FORM.step_1;
const FormGroup = props => {
const test = '';
return (
<div>
{myForm.controls.map(form => {
if (form.type === 'text') {
return (
<TextInput
{...form}
/>
);
}
if (form.type === 'dropdown') {
return (
<Dropdown
{...form}
/>
);
}
})}
</div>
);
};
export default FormGroup;
// dropdown component
interface IFormInput {
gender: GenderEnum;
}
enum GenderEnum {
female = "female",
male = "male",
other = "other",
}
const Dropdown = ({
question,
label,
prop,
style,
type,
options,
}) => {
const { register, handleSubmit } = useForm<IFormInput>();
const onSubmit: SubmitHandler<IFormInput> = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>{question && `${question}.`} {label}</label>
<select {...register("gender")}>
<option value="female">female</option>
<option value="male">male</option>
<option value="other">other</option>
</select>
<input type="submit" />
</form>
);
};
export default Dropdown;
// data object
export interface Form {
step_1: Controls
}
export interface Controls {
controls: Array<FormConfiguration>
}
export interface FormConfiguration {
question: number;
label: string;
prop: string;
type: string;
style: string;
placeholder?: string;
options?: any;
}
export const FORM: Form = {
step_1: {
controls: [
{
question: 75, // should this be a key or id?
label: 'Primary federal regulator',
prop: '',
style: '',
type: 'dropdown',
placeholder: 'Select a category',
options: [
{
label: 'FCC',
value: 'FCC',
},
{
label: 'FDA',
value: 'FDA',
},
],
},
{
question: 76,
label: 'Filer name (Holding compnay, lead financial institution, or agency, if applicable)',
prop: '',
style: '100%',
type: 'text',
},
{
question: 77,
label: 'TIN',
prop: '',
style: '50%',
type: 'text',
},
{
question: 78,
label: 'TIN type',
prop: '',
style: '50%',
type: 'text',
},
{
question: 80,
label: 'Type of Securities and Futures institution of individual filing this report - check box(es) for functions that apply to this report',
prop: '',
style: '',
type: 'checkbox',
options: [
{
label: 'Clearing broker-securities',
value: 'clearing broker-securities',
},
{
label: 'CPO/CTA',
value: 'CPO/CTA',
},
],
},
],
},
};
Your Dropdown component expects options as one of its props. You can either add a default value to make it optional, or fully type the props of the component, marking options as optional.
Approach #1 - default value:
const Dropdown = ({
question,
label,
prop,
style,
type,
options = [],
})
Approach #2 - typed props:
type Option = {
label: string;
value: string;
};
type Props = {
question: number;
label: string;
prop: string;
style: string;
type: string;
options?: Option[]; // note the question mark, which marks the prop as optional
...
};
const Dropdown = ({
question,
label,
prop,
style,
type,
options,
}: Props)
PS. I noticed you already have a type FormConfiguration (albeit options is using any which should be avoided). You can use that for the component by replacing : Props with : FormConfiguration in the example #2 above.
I managed to reproduce your problem in a much shorter example
interface FormConfiguration {
question: string
options?: any;
}
const simpleForm:FormConfiguration = {
question: "why options is required?"
}
function print({question, options}){
console.log(question, options);
}
function print_working({question, options}:FormConfiguration){
console.log(question, options);
}
print(simpleForm); // has you problem
print_working(simpleForm); //problem resolved
full code Playground Link
so the solution for you is to define the type of Dropdown function arguments. DropDown = ({...}: FormConfiguration)
I'm trying to get rid of a warning in my project:
react-dom.development.js?61bb:67 Warning: Prop `id` did not match. Server: "t4j6jv-aria" Client: "v0lutu9-aria"
Unfortunately I have no idea what's causing the problem, any help or help appreciated.
This is what line 60 looks at in CasinoList.tsx:
this is line #60:
Some Code prior to line 60:
interface IProps {
country: string;
flag: string;
casinoComments: {
id: number;
commentId: number;
content: string;
created: string;
likes: number;
author: string;
};
}
interface IState {
slug: String;
selectedLanguage: String;
visible: Boolean;
showList: Boolean;
highlightedHobby: Boolean;
isMobile: Boolean;
tagItems: Array<tagItems>;
activeTag: String;
tagId: Number;
}
interface tagItems {
id: number;
label: String;
name: String;
state: Boolean;
}
export default class FeaturedCasinos extends React.Component<
IProps,
IState,
{ country: String; flag: String }
> {
constructor(props: IProps) {
super(props);
Any ideas?
I'm trying to use the Select component from react-component with typescript but I got some overload errors. Below the snippet of my code:
type SelectedProps = {
name: string;
label: string;
placeholder: string;
readOnly: boolean;
options: {
label: string;
value: string
}
}
export function SelectFormik({ label, options, ...rest }: SelectedProps): ReactElement<any> {
const [field, meta, helpers] = useField(rest) // <-- Had set some type here I guess
const handleChange = (selected: SelectedProps["options"], action) => {
helpers.setValue(selected)
}
return (
<Box mb="2">
<FormControl>
{ label && <FormLabel htmlFor={rest.name}>{label}</FormLabel>}
<Select
{...rest}
{...field}
options={options}
onChange={handleChange}
styles={selectStyles}
isClearable
isSearchable
/>
<FormErrorMessage isInvalid={!!meta.error}>{meta.error}</FormErrorMessage>
</FormControl>
</Box>
)
}
and the error I got:
(alias) class Select<OptionType extends OptionTypeBase = { label: string; value: string; }, T extends SelectBase<OptionType> = SelectBase<OptionType>>
import Select
No overload matches this call.
Overload 2 of 2, '(props: Pick<Props<{ label: string; value: string; }>, ReactText> & import("/Users/marcos/Desktop/fitup-next/node_modules/#types/react-select/src/stateManager").Props<{ ...; }> & import("/Users/marcos/Desktop/fitup-next/node_modules/#types/react-select/src/Select").Props<...>, context?: any): StateManager<...>', gave the following error.
Type '{ label: string; value: string; }' is not assignable to type 'OptionsType<{ label: string; value: string; }> | GroupedOptionsType<{ label: string; value: string; }> | undefined'.
Type '{ label: string; value: string; }' is not assignable to type 'GroupedOptionsType<{ label: string; value: string; }>'.
Overload 2 of 2, '(props: Pick<Props<{ label: string; value: string; }>, ReactText> & import("/Users/marcos/Desktop/fitup-next/node_modules/#types/react-select/src/stateManager").Props<{ ...; }> & import("/Users/marcos/Desktop/fitup-next/node_modules/#types/react-select/src/Select").Props<...>, context?: any): StateManager<...>', gave the following error.
...
I read the error but i couldn't understand, if you could help me I'll appreciate. Thanks fellows. Sorry, jr developer being jr developer, kkkk.
Your interface SelectedProps defines options as a single option object, when you meant for it to be an array of option objects. That's the source of the particular error that you've posted.
type SelectedProps = {
name: string;
label: string;
placeholder: string;
readOnly: boolean;
options: {
label: string;
value: string;
}[];
}
It also seems like the type of value that is passed into the onChange callback is any, so I'm not sure what that value actually is. Maybe setting the generic on useField would help to refine that.
I have a react form component that I'm trying to rewrite to typescript. I am trying to retrieve an object within another object in a for loop but I keep getting the following error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
I've attempted the solution presented in the following questions but I was still unable to have a working solution and I do not wish to set noImplicitAny to false in tsconfig.json:
TypeScript: Object.keys return string[]
TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'
element implicitly has an 'any' type because type '{0}' has no index signature.
The code in question is - The problematic area can be found near the bottom:
import React from 'react';
import Button from '../../UI/Button/Button';
import Input from '../../UI/Input/Input';
type Config = {
elementType: string;
elementConfig: {
type: string;
placeholder: string;
options: {
value: string;
displayValue: string;
};
};
value: string;
validation: {
required: boolean;
isEmail?: boolean;
minLength?: number;
};
valid: boolean;
touched: boolean;
fieldActive: boolean;
// [key: string]: string | Object;
}
interface SignInFormProps {
isSignIn: boolean;
}
interface SignInFormState {
controls: {
email: Config;
password: Config;
};
isSignUp: boolean;
[key: string]: boolean | Object | Config;
}
class SignInForm extends React.Component<SignInFormProps, SignInFormState> {
state = {
controls: {
email: {
elementType: 'input',
elementConfig: {
type: 'email',
placeholder: 'Your Email',
options: {
value: '',
displayValue: ''
},
},
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false,
fieldActive: false
},
password: {
elementType: 'input',
elementConfig: {
type: 'password',
placeholder: 'Password',
options: {
value: '',
displayValue: ''
},
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false,
fieldActive: false
}
},
isSignUp: true
}
private activateField = ( controlName: keyof SignInFormState['controls'] ) => {
do stuff...
}
...
render() {
const formElementsArray: {id: string, config: Config}[] = [];
// ################ The config value is causing the error ################
for ( let key in this.state.controls ) {
formElementsArray.push({
id: key,
config: this.state.controls[key] as Config
});
}
let form = formElementsArray.map( formElement => (
<Input
blur={ ( event ) => this.disableFocus(event, formElement.id) }
changed={ ( event ) => this.inputChangedHandler(event, formElement.id) }
elementConfig={formElement.config.elementConfig}
elementType={formElement.config.elementType}
fieldActive={formElement.config.fieldActive}
focus={ () => this.activateField(formElement.id) }
invalid={!formElement.config.valid}
key={formElement.id}
shouldValidate={formElement.config.validation.required}
touched={formElement.config.touched}
value={formElement.config.value} />
));
If anybody has any ideas on how to resolve this while having clearly defined types and without using any then that would be helpful.
First of all, there isn't a nice way to do this and it's still in discussion: https://github.com/Microsoft/TypeScript/issues/3500
Below are 2 potential ways to solve your issue.
Declare the key outside of the loop:
const formElementsArray: { id: string; config: Config }[] = [];
let key: keyof typeof this.state.controls;
for (key in this.state.controls) {
formElementsArray.push({
id: key,
config: this.state.controls[key],
});
}
Use Object.keys & cast the key to the desired type:
const formElementsArray: { id: string; config: Config }[] = (Object.keys(
this.state.controls
) as (keyof typeof this.state.controls)[]).map((key) => ({
id: key,
config: this.state.controls[key],
}));
You could also make it clearer by using an enum for the control key
enum ControlKey {
email = "email",
password = "password",
}
interface SignInFormState {
controls: {
[key in ControlKey]: Config;
};
isSignUp: boolean;
[key: string]: boolean | Object | Config;
}
then
1b.
const formElementsArray: { id: string; config: Config }[] = [];
let key: ControlKey;
for (key in this.state.controls) {
formElementsArray.push({
id: key,
config: this.state.controls[key],
});
}
or
2b.
const formElementsArray: { id: string; config: Config }[] = (Object.keys(
this.state.controls
) as ControlKey[]).map((key) => ({
id: key,
config: this.state.controls[key],
}));
Hope this helps
I am new to both React and TypeScript and am trying to make a simple React Data Grid based on their simple example here: https://adazzle.github.io/react-data-grid/docs/quick-start
Here is what I have:
import React from 'react';
import ReactDataGrid from 'react-data-grid';
const columns = [
{ key: "id", name: "ID", editable: true },
{ key: "title", name: "Title", editable: true },
{ key: "complete", name: "Complete", editable: true }
];
const rows = [
{ id: 0, title: "Task 1", complete: 20 },
{ id: 1, title: "Task 2", complete: 40 },
{ id: 2, title: "Task 3", complete: 60 }
];
export const DataTable: React.FC = () => {
return (
<ReactDataGrid
columns={columns}
rowGetter={i => rows[i]}
rowsCount={rows.length}
/>
);
};
However I keep getting an error on the link where it sets the columns in the table. It says:
(JSX attribute) DataGridProps<{ [x: string]: {}; }, React.ReactText>.columns: (ColumnValue<{
[x: string]: {};
}, unknown, string> | ColumnValue<{
[x: string]: {};
}, unknown, number>)[]
Type '{ key: string; name: string; editable: boolean; }[]' is not assignable to type '(ColumnValue<{ id: number; title: string; complete: number; }, unknown, "id"> | ColumnValue<{ id: number; title: string; complete: number; }, unknown, "title"> | ColumnValue<{ id: number; title: string; complete: number; }, unknown, "complete">)[]'.
Type '{ key: string; name: string; editable: boolean; }' is not assignable to type 'ColumnValue<{ id: number; title: string; complete: number; }, unknown, "id"> | ColumnValue<{ id: number; title: string; complete: number; }, unknown, "title"> | ColumnValue<{ id: number; title: string; complete: number; }, unknown, "complete">'.
Type '{ key: string; name: string; editable: boolean; }' is not assignable to type 'ColumnValue<{ id: number; title: string; complete: number; }, unknown, "complete">'.
Types of property 'key' are incompatible.
Type 'string' is not assignable to type '"complete"'.ts(2322)
DataGrid.d.ts(6, 5): The expected type comes from property 'columns' which is declared here on type 'IntrinsicAttributes & DataGridProps<{ id: number; title: string; complete: number; }, "id" | "title" | "complete"> & { ref?: ((instance: DataGridHandle | null) => void) | RefObject<...> | null | undefined; }'
Can anyone help me parse this error? Do I need to explicitly set the type of the columns to the type that the react data grid is expecting?
I installed the react-data-grid types and the error went away:
npm install --save #types/react-data-grid