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

根据他们的回复,我有一个适用于我的情况的解决方案。我对他们的答案的唯一问题是,我需要从外部键入要传递给函数的内容,但无法找到一种方法来推断键而不在函数中。在我的情况下,使用 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}</>

}


隔江千里
浏览 117回答 1
1回答

千巷猫影

我认为如果我们稍微简化一下这个例子,我们可以理解我们想要做什么:interface ITest {&nbsp; n: number;&nbsp; b: boolean;}const f = <K extends keyof ITest>(&nbsp; x: {&nbsp; &nbsp; id: K,&nbsp; &nbsp; params: ITest[K],&nbsp; },) => true;f({ id: 'n', params: 1 });&nbsp; &nbsp; // no type errorf({ id: 'n', params: true }); // Type 'true' is not assignable to type 'number'f({ id: 'b', params: true }); // no type errorf({ id: 'b', params: 1 });&nbsp; &nbsp; // Type 'number' is not assignable to type 'boolean'我们可以指定一些泛型(在上面的示例中)扩展该类型的键。然后,我们可以使用该密钥来获取我们正在寻找的类型。K
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript