为什么在这种情况下TypeScript泛型不能自动正确完成?

gojuced7  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(83)

为什么TypeScript在这种情况下不能正确地假设变量“setSortableFields”类型?
在下面代码的注解部分提供了更多细节

export type TesteProps<
    SortableFields extends (true|false)
> = (
    {
        pending: boolean,
        sortedFields: object,
        sortableFields: SortableFields
    }
    ) & (
    SortableFields extends true ? {
        setSortedFields: object
    } : {
        setSortedFields?: never
        }

    );

export function Teste<
    SortableFields extends (true|false)
>(
    props: TesteProps<SortableFields>
) {
    if (props.sortableFields) {

        const setSortableFields /* here it auto completes with (Object | undefined) instead of assuming it as an Object since the "sortableFields" param is true */ = props.setSortedFields;
        console.log(setSortableFields);
    }
    return <>{JSON.stringify(props)}</>;
}

字符串

fumotvh3

fumotvh31#

1.我想你应该用另一种方式声明泛型,以避免在你的类型使用过程中重新声明它。(我不知道这是必要的还是仅仅是美观的改进)
1.老实说,我不能提供答案的问题"为什么"。我也经常有这样的期望,所以问题.但下面的代码是工作

// to avoid type duplication - declare this same part of both scenarios into separate type
// instead of B extends boolean write B = boolean
// the same as B extends boolean = boolean
type SharedType<B = boolean> = {
  pending: boolean;
  sortedFields: object;
  sortableFields: B;
};
// also use "=" instead of "extends"
export type TesteProps<
  SortableFields = boolean,
> = SortableFields extends true ? SharedType<SortableFields> & {
    setSortedFields: object;
  }
  : SharedType<SortableFields>;

// your type coputes in code and no impact on return type
// so I remove unusable generic from function's defenition 
export function Teste(
  props: TesteProps,
) {
  if (!props.sortableFields) {
    const setSortableFields /* now typescript Error (only with ".sortableFields = true" in if-block no error) */ =
      props.setSortedFields;
    console.log(setSortableFields);
  }
  return <>{JSON.stringify(props)}</>;
}

字符串

相关问题