【问题标题】:Typescript: Dynamically check the second argument keys doesn't exists on first argument打字稿:动态检查第二个参数键在第一个参数上不存在
【发布时间】:2021-11-20 10:54:46
【问题描述】:

我有一个接受两个参数的函数。基本上我希望 Typescript 进行检查,第二个参数不能包含第一个参数中的键。 TS Sandbox


interface Todo {
  title: string;
  description: string;
}
    
// here I hardcoded the 'title' key on the Omit utility type. My question is, how to make this dynamic, based on the key on the left argument.
function test<T>(left: Partial<T>, right: Partial<Omit<T, 'title'>>): void {
  console.log(left, right);
};
    
// expected TS error here, because title already exists on the left object
test<Todo>({ title: 'A' }, { description: 'B', title: 'AB' })

任何帮助将不胜感激..

【问题讨论】:

  • let title = "Hello world"; let description = "你好世界,欢迎来到宇宙。";然后像这样使用includes()函数:description.includes(title)

标签: typescript type-constraints


【解决方案1】:

如果一个额外的泛型没有帮助,请添加另一个 :) 每当我遇到泛型问题时,这条规则都会帮助我。

看这个例子:

interface Todo {
  title: string;
  description: string;
}

const test = <
  Left extends Todo,
  PartialLeft extends Partial<Left>>
  (left: PartialLeft, right: Partial<Omit<Left, keyof PartialLeft>>) => { }

test({ title: 'A' }, { description: 'B', title: 'AB' }) // expected error

test({ description: 'A' }, { description: 'B', title: 'AB' }) // expected error

Left - 推断出第一个参数,而后者又应该扩展 Todo

PartialLeft - 推断文字参数类型

Partial&lt;Omit&lt;Left, keyof PartialLeft&gt;&gt; - 表示第二个参数应该在 Left 通用参数中省略来自 PartialLeft 的所有道具。

PartialLeft 在此功能中起着关键作用。这个泛型代表第一个参数。 如果您想了解有关函数参数类型推断的更多信息,可以查看我的article

Playground

【讨论】:

  • 感谢您的回答。但是有没有办法通过多种类型/接口(具有不同键的对象文字)使这种动态变化。例如,我还有另一个 interface Task { name: string; time: string; } 。如果我这样做test&lt;Task&gt;({ name: 'A' }, { name: 'B', { time: '10:10' }) 的想法应该会在不更改函数签名的情况下引发错误。
  • 您应该知道,使用没有相应值的显式泛型是不安全的。请看这个stackoverflow.com/questions/69431436/…,这个stackoverflow.com/questions/69187022/…和这个catchts.com/infer-arguments
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2021-11-11
  • 1970-01-01
  • 2022-01-26
  • 2019-01-22
  • 2018-03-22
  • 1970-01-01
相关资源
最近更新 更多