我有以下代码:
interface Data {
[x: string]: number;
}
type Unpacked<T> = T extends (infer U)[]
? U
: T extends (...args: any[]) => infer U
? U
: T extends Promise<infer U>
? U
: T;
interface Props<T extends Data[]> {
data: T
xLabel: Extract<keyof Unpacked<T>, string>;
yLabel: Extract<keyof Unpacked<T>, string>;
}
const Chart = <T extends Data[]>({ data, xLabel, yLabel }: Props<T>): ReactElement => {
const styles = useStyles();
return (
<View style={styles.container}>
<VictoryChart width={350} theme={VictoryTheme.material}>
<VictoryArea data={data} x={xLabel} y={yLabel} />
<VictoryAxis />
</VictoryChart>
</View>
);
};
const data = [
{ quarter: 1, earnings: 13000 },
{ quarter: 2, earnings: 16500 },
{ quarter: 3, earnings: 14250 },
{ quarter: 4, earnings: 19000 },
];
const Home = (): ReactElement => {
const styles = useStyles();
return (
<ScrollView
showsVerticalScrollIndicator
>
<Block>
<Chart data={data} xLabel="abc" yLabel="earnings" />
</Block>
</ScrollView>
);
};
根据我的理解,xLabel =“ abc”应该导致错误,因为它不是数据的键(仅在这种情况下为“季度”或“收入”)。但是,不幸的是,xLabel和yLabel是“字符串”的类型,这不是我期望的。我做错了什么吗?