最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Typescript assignment narrowing "type | type[]" not working - Stack Overflow

programmeradmin1浏览0评论
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.

发布评论

评论列表(0)

  1. 暂无评论