为了账号安全,请及时绑定邮箱和手机立即绑定

如何在类型脚本查找中匹配键和值

如何在类型脚本查找中匹配键和值

隔江千里 2022-09-23 16:40:05
根据他们的回复,我有一个适用于我的情况的解决方案。我对他们的答案的唯一问题是,我需要从外部键入要传递给函数的内容,但无法找到一种方法来推断键而不在函数中。在我的情况下,使用 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 errorconst b: Props = f({ id: "n", params: true }); // Type 'true' is not assignable to type 'number'const c = f({ id: "b", params: true }); // no type errorconst 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 noticingconst z: Props = {  // Property '_propToConfirmYourUsingTheUtilNeverWriteThisManually' is missing in type ...  id: "b",  params: 7,};f(a); // no type errorf(b); // no type errorf(c); // no type errorf(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 typefunction Text(props: Props) {  const text = intlFunctionThatGetsTheTranslatedText(props.id, props.params);  return <>{text}</>}
查看完整描述

1 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

我认为如果我们稍微简化一下这个例子,我们可以理解我们想要做什么:


interface ITest {

  n: number;

  b: boolean;

}


const f = <K extends keyof ITest>(

  x: {

    id: K,

    params: ITest[K],

  },

) => true;


f({ id: 'n', params: 1 });    // no type error

f({ id: 'n', params: true }); // Type 'true' is not assignable to type 'number'


f({ id: 'b', params: true }); // no type error

f({ id: 'b', params: 1 });    // Type 'number' is not assignable to type 'boolean'

我们可以指定一些泛型(在上面的示例中)扩展该类型的键。然后,我们可以使用该密钥来获取我们正在寻找的类型。K


查看完整回答
反对 回复 2022-09-23
  • 1 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号