Solve the typescript - "No matches overload call" with ref - reactjs

I am going to solve the typescript correspondent.
Here is the code and the error what I got.
const navRef = useRef<null | HTMLElement>(null);
const setFocusables = () => {
let navCurrent = navRef.current || null;
menuFocusables = [
buttonRef.current,
...Array.from(navCurrent?.querySelectorAll('a')),
];
firstFocusableEl = menuFocusables[0];
lastFocusableEl = menuFocusables[menuFocusables.length - 1];
};
Here is the error what I got it now.
let navCurrent: HTMLElement | null No overload matches this call.
Overload 1 of 4, '(iterable: Iterable |
ArrayLike): HTMLAnchorElement[]', gave the
following error. Argument of type 'NodeListOf
| undefined' is not assignable to parameter of type
'Iterable | ArrayLike'.
Type 'undefined' is not assignable to type
'Iterable | ArrayLike'.
Overload 2 of 4, '(arrayLike: ArrayLike):
HTMLAnchorElement[]', gave the following error. Argument of type
'NodeListOf | undefined' is not assignable to
parameter of type 'ArrayLike'. Type
'undefined' is not assignable to type
'ArrayLike'.ts(2769)
Please give me solution.
Thank you in advance.
Hi.
I hope to solve the above problem.
Thanks

You need to handle when navCurrent is null, so it should be like:
const navRef = useRef<null | HTMLElement>(null);
const setFocusables = () => {
let navCurrent = navRef.current || null;
menuFocusables = [
buttonRef.current,
// updated this
...Array.from(navCurrent?.querySelectorAll('a') ?? []),
];
firstFocusableEl = menuFocusables[0];
lastFocusableEl = menuFocusables[menuFocusables.length - 1];
};

Related

Error: Cannot create styled-component for component: undefined

j
X:/rstfrontend/packages/src/constants.js:4
1 | // #flow
2 |
3 | declare var SC_DISABLE_SPEEDY: ?boolean;
> 4 | declare var __VERSION__: string;
5 |
6 | export const SC_ATTR: string =
7 | (typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR)) ||
Another problem is that it refers to a path that doesn't exist.
When clicked on View Compiled it links to main.chunk.
Maybe a bug with webpack?
j
http://localhost:3000/static/js/vendors~main.chunk.js:187248:30
187245 | n[r - 1] = arguments[r];
187246 | }
187247 |
> 187248 | throw false ? undefined : new Error(D.apply(void 0, [R[e]].concat(n)).trim());
| ^ 187249 | }
187250 |
187251 | var T = function () {

Material-UI DateRangePicker TypeScript Error Can't use (Date | null)[] for DateRange<any>

TypeScript error in C:/**.tsx(109,45):
Argument of type '(Date | null)[]' is not assignable to parameter of type 'SetStateAction<DateRange<any>>'.
Type '(Date| null)[]' is not assignable to type '(prevState: DateRange<any>) => DateRange<any>'.
Type '(Date | null)[]' provides no match for the signature '(prevState: DateRange<any>): DateRange<any>'. TS2345
107 | console.log('Submitted Dates:', newValue);
108 | console.log('Corrected Dates:', utcCorrectedDates);
> 109 | setCarrierTransactionDate(utcCorrectedDates);
| ^
110 | }}
111 | onError={(
112 | errorReason: DateRangeValidationError,
Full Function is
onChange={(newValue: DateRange<any>) => {
const utcCorrectedDates = newValue.map(date => {
if (date) return convertMissDatedToUTC(date);
return null;
});
console.log('Submitted Dates:', newValue);
console.log('Corrected Dates:', utcCorrectedDates);
setCarrierTransactionDate(utcCorrectedDates);
}}
I see the type def of DateRange is
export declare type DateRange<TDate = unknown> = [TDate | null, TDate | null];
my type def of convertMissDatedToUTC is
convertMissDatedToUTC = ( origDate: string | Date | null ): Date | null
I can't for the life of me figure out how to convert this new array to DateRange.
Basically the problem I am trying to fix is the DateRangePicker is creating values like this since my Client is in the Central Time Zone:
[
"2022-01-13T06:00:00.000Z",
null
]
When I need them to be UTC:
[
"2022-01-13T00:00:00.000Z",
null
]
So I created the function to fix these values.
const convertMissDatedToUTC = (
origDate: string | Date | null
): Date | null => {
if (origDate === null) return null;
const tzDateObj = new Date(origDate);
const utcDateObj = new Date();
utcDateObj.setUTCFullYear(tzDateObj.getFullYear());
utcDateObj.setUTCMonth(tzDateObj.getMonth());
utcDateObj.setUTCDate(tzDateObj.getDate());
utcDateObj.setUTCHours(tzDateObj.getHours());
utcDateObj.setUTCMinutes(tzDateObj.getMinutes());
utcDateObj.setUTCSeconds(tzDateObj.getSeconds());
utcDateObj.setUTCMilliseconds(tzDateObj.getMilliseconds());
return utcDateObj;
};

Access multiple nested TypeScript type generated from GraphQL

I need to access only the "departments" type in this large type generated from GraphQL:
export type GetCompanyChartQuery = (
{ __typename?: 'Query' }
& { generateOrgChart?: Maybe<(
{ __typename?: 'DepartmentNode' }
& Pick<DepartmentNode, 'name'>
& { manager?: Maybe<(
{ __typename?: 'EmployeeNode' }
& Pick<EmployeeNode, 'name' | 'mobilePhone'>
)>, departments?: Maybe<Array<Maybe<(
{ __typename?: 'DepartmentNode' }
& Pick<DepartmentNode, 'name' | 'depth'>
& { manager?: Maybe<(
{ __typename?: 'EmployeeNode' }
& Pick<EmployeeNode, 'name'>
)>, employees?: Maybe<Array<Maybe<(
{ __typename?: 'EmployeeNode' }
& Pick<EmployeeNode, 'imageUrl' | 'mobilePhone' | 'name' | 'position' | 'title' | 'depth'>
)>>>, departments?: Maybe<Array<Maybe<(
{ __typename?: 'DepartmentNode' }
& Pick<DepartmentNode, 'name' | 'depth'>
& { manager?: Maybe<(
{ __typename?: 'EmployeeNode' }
& Pick<EmployeeNode, 'name'>
)>, employees?: Maybe<Array<Maybe<(
{ __typename?: 'EmployeeNode' }
& Pick<EmployeeNode, 'imageUrl' | 'mobilePhone' | 'name' | 'position' | 'title' | 'depth'>
)>>> }
)>>> }
)>>> }
)> }
);
I cannot find a way around this. Pick<GetCompanyChartQuery, 'subType'> or GetCompanyChartQuery['subtype'] wont do the trick here.
I am trying to fetch data with a GraphQL query and put the response in a state like this:
const [departments, setDepartments] = useState<TheTypeINeedToAccess>();
setDepartments(data?.generateOrgChart?.departments);
But to do this I need the correct type.
Thanks in advance.
I think the issue with picking the subtypes is the optional properties. If you make the object non-nullish, TypeScript can pick out the subtype.
type Departments = Required<GetCompanyChartQuery>["generateOrgChart"]["departments"]

How to define a binding that accepts multiple types in the function signature using reason-react?

When defining a reason-react binding and I want to know how I can determine a binding that accepts multiple types. For example, I have an argument ~value that should accept: string, number, array(string) or array(number). At the moment I am using option('a) but I do not think this is the cleanest approach as I would prefer to define the type explicitly. How can this be done? I have looked at bs.unwrap but I am unsure how to combine external syntax into a function signature.
module Select = {
[#bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value: option('a), /* Should be type to string, number, Array of string and Array of number */
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(value),
"style": from_opt(style)
}
),
children
);
};
As a side question, as number type is not defined in reason would my binding also have to map float and integer into numbers?
This is possible by using the following (inspired by https://github.com/astrada/reason-react-toolbox/).
type jsUnsafe;
external toJsUnsafe : 'a => jsUnsafe = "%identity";
let unwrapValue =
(r: [< | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]) =>
switch r {
| `String(s) => toJsUnsafe(s)
| `Int(i) => toJsUnsafe(i)
| `StringArray(a) => toJsUnsafe(a)
| `IntArray(a) => toJsUnsafe(a)
};
let optionMap = (fn, option) =>
switch option {
| Some(value) => Some(fn(value))
| None => None
};
module Select = {
[#bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value:
option(
[ | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]
)=?,
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(optionMap(unwrapValue, value)),
"style": from_opt(style)
}
),
children
);
};
This can be used in the following way;
<Select value=(`IntArray([|10, 20|])) />
<Select value=(`Int(10)) />
I copied toJsUnsafe from reason-react-toolbox, so I'm not entirely sure exactly what it does, I will update my answer when I find out.
The unwrapValue function takes a value which can be one of the types listed and converts it to jsUnsafe.
The type for unwrapValue allows for any of variants listed, but also allows a subset of those, for example. (It's the < before the variants that enable this).
let option = (value: option([ | `String(string) | `Int(int)])) =>
Js.Nullable.from_opt(option_map(unwrapValue, value));
Just to add to #InsidersByte's answer, since this problem isn't reason-react-specific and can be generalized:
module Value = {
type t;
external int : int => t = "%identity";
external intArray : array(int) => t = "%identity";
external string : string => t = "%identity";
external stringArray : array(string) => t = "%identity";
};
let values : list(Value.t) = [
Value.int(4),
Value.stringArray([|"foo", "bar"|])
];
This solution is also self-contained inside the Value module, and incurs no overhead compared to the JavaScript equivalent since "%identity" externals are no-ops that are optimized away.

Need help to make [create-react-app] to use Aync - Await (transform-async-to-generator)!

I am new to [create-react-app] and I would like to find out how can I add : ["transform-async-to-generator"] to this build process? In regular cases I would add it in .babelrc, but does not look to work* with [create-react-app].
*By "does not look to work" - I see the following error.
Syntax error: ../web/src/App.js: Unexpected token, expected ( (17:13)
15 | }
16 |
> 17 | test = async () => {
| ^
18 | let x = await this.resolveAfter2Seconds();
19 | try{}
20 | catch(exception){
And is any way to extend [create-react-app], without modifying the package itself?
Thanks!
The problem is not with async functions. You should rewrite your code the next way:
// ...
test = async () => {
let x = await this.resolveAfter2Seconds();
// ...
}
or
// ...
async test(){
let x = await this.resolveAfter2Seconds();
// ...
}
You should add 2 plugins to babel: babel-plugin-transform-async-to-generator and babel-plugin-syntax-async-functions

Resources