为什么类型被推断而泛型参数是可选的

问题描述 投票:0回答:1

我有以下情况。我想将 GridSelectProps 的输入限制为作为通用参数及其键传递的类型。但是,通用参数不是强制性的。如果我不通过,则所有条目都是可能的,如果我通过,则限制按预期工作。

我认为这是一个简单的故事,但不知何故,如果未指定通用参数,它将被解释为字符串,如果指定了参数,则它仅限于键。

我怎样才能达到我想要的行为?我希望通用参数成为强制规范,因此只有可用作此类型键的输入是可能的。

interface Person {
  Id: number;
  Name: string;
}

interface Props<T> {
  readonly dataItemKey: keyof T & string;
}

const GridSelectProps = <T>({ dataItemKey }: Props<T>): GridProps => {
  return {
    dataItemKey,
  };
};

const somePropsWithout = GridSelectProps({
  dataItemKey: "Test" // compiler does not complain
});

const somePropsWith = GridSelectProps<PdsrOverviewItem>({
  dataItemKey: "Id", // compiler assignment check works as expected
});

代码沙盒游乐场

typescript generics type-inference
1个回答
0
投票

写作

const GridSelectProps = <T>({ dataItemKey }: Props<T>): GridProps =>

使

T
成为 generic constraint,其中 TS 试图弄清楚
T
是什么,如果没有指定的话。

所以当你写的时候

const somePropsWithout = GridSelectProps({
  dataItemKey: "Test"
});

假设

T
{Test: any}
并且一切正常。

您可以将

Props<T>
拉入约束中以避免这种情况:

const GridSelectProps = <T, P extends Props<T> = Props<T>>({ dataItemKey }: P): GridProps => {
  return {
    dataItemKey
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.