Cannot get object property because property width is missing in undefined - javascript

I have this glamor css function, this function when i tried to run flowJS, this function have an error like this, where size? is an object that have padding and width as a string.
Error ------------------------------------------------------------ src/Components/Button/Button.component.style.js:38:17
Cannot get size.width because property width is missing in undefined [1]. [incompatible-use]
[1] 34| size?: Option
35| ): $Shape<CSSStyleDeclaration> =>
36| compose(baseStyle, {
37| backgroundColor: bgColor,
38| width: size.width,
39| padding: size.padding,
40| color: textColor
41| });
My css glamor function :
export const setStyleButton = (
bgColor?: string,
textColor?: string,
size?: Option
): $Shape<CSSStyleDeclaration> =>
compose(baseStyle, {
backgroundColor: bgColor,
width: size.width,
padding: size.padding,
color: textColor
}`);
My Flow Type :
// #flow
export type Option = {|
padding:string,
width:string
|}
export type Options = {|
[key:string] : Option
|}
export type Props = {|
name: string,
color?: string,
textColor?: string,
size?: Option,
onPress: () => void,
disabled: boolean,
|};
can someone help me to fix my problem how to defined object property on flowjs

Related

React component generic type expected 0 type arguments but got 1

type TCommonField = {
label?: string,
dataKey?: string,
required?: boolean,
loading?: boolean,
placeholder?: string,
getListOptionsPromissoryCallback?: unknown,
listingPromissoryOptions?: unknown,
renderOption?: unknown,
getOptionLabelFormat?: unknown,
onChange?: (...args: unknown[]) => unknown,
validationCallback?: (...args: unknown[]) => unknown,
}
export type TField<fieldTypeT = any> = FC<TCommonField & fieldTypeT> & {
types?: Record<string, unknown>,
};
I'm creating a type declaration for Field function component with TField type. Field is a function component to render different types of fields(select, autocomplete, text field...)
There are common fields which all fields shared, so I've created TCommonField type, and there're some specific fields per fields.
I've created TField type with generic fieldTypeT, so that each Field can pass the type and it will be combined with common types.
<Field<{ tabIndex: number }> => Expected 0 type arguments, but got 1.ts(2558)
dataKey="dataKey"
placeholder="Some place holder"
tabIndex={-1}
/>
Field is a JS component
declare function useForm<formValuesT = Record<string, unknown>>(
initialValues?: formValuesT,
config? : TUseFormOptions
): TUseFormResponse<formValuesT>;
type TUseFormResponse<formValuesT = Record<string, unknown>> = {
values: formValuesT,
isPassing: boolean,
formError: string | null,
fieldErrors: TFieldErrors,
dataHasChanged: boolean,
triggerScrollCheck: () => void,
setServerErrors: TServerErrorCallback,
} & { Field: TField };
Updated typescript lang with two fields
You'd need to specify fieldTypeT in useForm, so it can return the correct type of TField.
This typechecks out fine.
import React from 'react';
type TCommonField = {
label?: string,
placeholder?: string,
}
export type TField<fieldTypeT> = React.FC<TCommonField & fieldTypeT> & {
types?: Record<string, unknown>,
};
type TUseFormResponse<fieldTypeT, formValuesT = Record<string, unknown>> = {
values: formValuesT,
Field: TField<fieldTypeT>,
};
declare function useForm<fieldTypeT, formValuesT = Record<string, unknown>>(
initialValues?: formValuesT,
): TUseFormResponse<fieldTypeT, formValuesT>;
const DirectBookingWizard = () => {
const {Field} = useForm<{tabIndex: number}, { value?: string }>({});
return (
<Field
label='label'
placeholder='placeholder'
tabIndex={-1}
/>
)
}

Can't access property when using a |

Here's my code:
type DetailsItemEditInput = {
type: 'text' | 'number';
};
type DetailsItemEditDropdown = {
type: 'dropdown';
options: [];
};
type DetailsItemEdit = DetailsItemEditDropdown | DetailsItemEditInput;
export const DetailsItemEdit: FC<DetailsItemEdit> = ({ type, ...props }) => {
switch (type) {
case 'text' || 'number':
return <Input type={type} />;
case 'dropdown':
return <Select options={props.options} />;
default:
return <div style={{ color: 'red' }}>Wrong type</div>;
}
};
What I'm trying to achieve:
I want the options property to be required, only when the type is a 'dropdown'. I thought I might do this with a |. But unfortunately, props doesn't seem to have the options property in the <Select .../> part. What am I missing?
Property 'options' does not exist on type '{ children?: ReactNode; } | { options: []; children?: ReactNode; }'.
Property 'options' does not exist on type '{ children?: ReactNode; }'.ts(2339)
TypeScript is not smart enough to narrow the type of the props in your code. If you do not destructure the props the code should work.

How to get a more specific type from "object type" in flow?

Well consider the following code:
class base<T: {[string]: any}> {
field: T;
}
type SpecificTy = {|
val: number,
field: string,
|}
class subclass<T = SpecificTy> extends base<T> {}
This gives the following error:
`T` [1] is incompatible with object type [2] in type argument `T`. [incompatible-type-arg]
How would I create a type that is "object with just attributes x,y and z" to provide to a base class that accepts "any object"?
This works if you make your object types read-only:
class base<T: { +[string]: any }> {
field: T;
}
type SpecificTy = $ReadOnly<{|
val: number,
field: string,
|}>;
class subclass<T: SpecificTy> extends base<T> {}
Try Flow
Or if you don't include the index type:
class base<T: {}> {
field: T;
}
type SpecificTy = {|
val: number,
field: string,
|};
class subclass<T: SpecificTy> extends base<T> {}
Try Flow

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type A

Type A in the question is referring to in this example BadgeTypes type
and full error is
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type A.No index signature with a parameter of type 'string' was found on type A
Sandbox Link:
https://codesandbox.io/s/typescript-type-checking-question-hkfmc
(NOTE: But for some reason it did not show the error -_-)
I am having problem come out a proper fix. and all the sorta relevant posts are going over my head. Would appreciate an answer accompany with explanations
type BadgeTypes = {
success: string;
secondary: string;
alert: string;
text: string;
};
type Theme = {
fonts?: object;
borderRadius?: string;
primary?: object;
accent?: object;
action?: object;
stories?: object;
checkbox?: object;
badge: BadgeTypes;
button?: object;
page?: object;
states?: object;
modal?: object;
};
interface Props {
theme: Theme;
large: boolean;
type: keyof BadgeTypes;
}
const StyledBadge = styled.span<Props>`
display: inline-block;
border-radius: ${(props: Props) => props.theme.borderRadius};
text-align: center;
color: ${(props: Props) => props.theme.badge.text};
font-size: ${(props: Props) => (props.large ? `1.4rem` : `1rem`)};
padding: ${(props: Props) =>
props.large ? `0 .8rem` : `0.2rem 0.6rem 0.3rem 0.6rem`};
// error happens here
background: ${(props: Props) => props.theme.badge[`${props.type}`]};
`;
The problem is using a template string to index badge.
Basically:
// this is a string
let x = `${props.type}`;
// this is "success" | "secondary" | "alert" | "text"
let y = props.type;
If you write props.theme.badge[props.type] the type checker should be happy.

What is causing these TypeScript Element errors with this array of React components

Can anyone please advise on what is causing and how to fix the following TypeScript errors I am getting with an array of returned Button components. Here is the relevant Button component code:-
type type = 'primary' | 'secondary' | 'tertiary' | 'tertiary_variant';
type size = 'base' | 'small' | 'micro';
type Props = typeof Button.defaultProps & {
type: type;
size: size;
className: string;
disabled: boolean;
busy: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
children: any;
attributes: any;
submitButton: boolean;
};
type ButtonRipple = {
top: number;
left: number;
id: string;
}
type State = {
ripples: ButtonRipple[];
}
class Button extends Component<Props, State> {
static defaultProps = {
type: 'primary',
size: 'base',
className: null,
disabled: false,
busy: false,
attributes: {},
submitButton: false
};
private readonly buttonRef: React.RefObject<unknown>;
constructor(props: Props) {
super(props);
this.buttonRef = React.createRef();
this.state = {
ripples: []
};
}....
Here is the function from the parent component that returns the Buttons:-
generateButtons = (): Button[] => {
return [
254 <Button
key="cancel"
type="tertiary"
onClick={this.props.onClose}
attributes={{
'aria-label': 'Cancel'
}}
>
Cancel
</Button>,
265 <Button
key="submit"
onClick={this.handleSubmit}
attributes={{
'aria-label': 'Submit'
}}
className={styles.submitButton}
>
Submit
</Button>
];
};
And here are the errors:-
Error:(254, 13) TS2740: Type 'Element' is missing the following properties from type 'Button': buttonRef, handleClick, createRipple, render, and 5 more.
Error:(265, 13) TS2322: Type 'Element' is not assignable to type 'Button'.
Thanks,
Sam
The root cause of your problem is that <Button .../> is not an instance of Button, instead it's a JSX.Element. If you need a reference to a Button to access its methods, you can use the ref mechanism in React.
To explain why the errors are so cryptic, typescript allows assigning objects of one class to references of another, as long as their interfaces match. In your case JSX.Element doesn't implement all requirements for the Button interface.

Categories

Resources