declare function foo(first: myType[]): void;
type myType = {};
function x(param: myType | myType []): void {
param = [];
foo(param);
}
This code gives me a typechecking error on calling foo():
param could be myType | myType[]
Even though I assigned it to an array which should have narrowed it. I though typescript could do assignment narrowing? This only gives the error if I use the myType
definition. If I change the definition to be a string | string[]
, it seems to successfully narrow down the param:
declare function foo(first: string[]): void;
type myType = {};
function x(param: string | string[]): void {
param = [];
foo(param);
}
I first encountered this problem in my react app:
useAutoCycle()
takes a first parameter of ReactNode[]
and the second as a number.
import useAutoCycle from '@/hooks/useAutoCycle';
import { ReactNode } from 'react';
interface Props {
children: ReactNode[] | ReactNode;
/** Delay between content changes in milliseconds */
delay: number;
}
function CycleHeader({ children, delay }: Props): JSX.Element {
if (!Array.isArray(children)) {
children = [children] as ReactNode[];
}
const currentContent = useAutoCycle(children, delay);
return <>{currentContent}</>;
}
export default CycleHeader;
I understand that I can always type assert on calling the functions. I'm curious as to why for my own type I cannot do type assertions to the array of itself.