根据他们的回复,我有一个适用于我的情况的解决方案。我对他们的答案的唯一问题是,我需要从外部键入要传递给函数的内容,但无法找到一种方法来推断键而不在函数中。在我的情况下,使用 util 为我们做这件事是可以的,如下所示:
interface ITest {
n: number;
b: boolean;
}
const f = <K extends keyof ITest>(x: { id: K; params: ITest[K] }) => ({
...x,
_propToConfirmYourUsingTheUtilNeverWriteThisManually: true,
});
type Props = ReturnType<typeof f>;
const a: Props = f({ id: "n", params: 1 }); // no type error
const b: Props = f({ id: "n", params: true }); // Type 'true' is not assignable to type 'number'
const c = f({ id: "b", params: true }); // no type error
const d = f({ id: "b", params: 1 }); // Type 'number' is not assignable to type 'boolean'
// Errors because we didn't add _propToConfirmYourUsingTheUtilNeverWriteThisManually
// This ridiculously named prop should ensure we don't override it without noticing
const z: Props = {
// Property '_propToConfirmYourUsingTheUtilNeverWriteThisManually' is missing in type ...
id: "b",
params: 7,
};
f(a); // no type error
f(b); // no type error
f(c); // no type error
f(d); // no type error
更新:
这种情况可以过去:
const invalidProps1: Props<IdsWithParameters> = {
id: "id1",
params: {
param1: "string",
},
};
其他属性不是此代码之外的代码的问题。但是,为了使这个组件函数能够是通用的,并采用任何id,我们不能像@oliverradini回复那样显式指定密钥。但是他们的帮助使我接近这一点,但仍然不完全存在。IdsWithParametersProps<'id1'>
interface Props<K extends keyof IdsWithParameters> {
id: K;
params: IdsWithParameters[K];
}
// Somehow want Props to know what is being used as the id and infer
// the correct params type
function Text(props: Props) {
const text = intlFunctionThatGetsTheTranslatedText(props.id, props.params);
return <>{text}</>
}
千巷猫影
相关分类