"supplied parameters do not match call signature of target"的简单打字稿示例



我正在学习打字稿,并且一直在此示例上工作:

interface Thing {
    a: number;
    b: boolean;
    c: string;
}
let obj = <Thing>{
    a: 5,
    b: true,
    c: 'string that says string'
}
function x(someObj: Thing): string {
    return someObj.c;
}
function func(someObj: Thing, x: () => string) {
    return x(someObj);
}
console.log(func(obj, x))

我在func函数中的返回语句中以及最后一行的func中的x中都遇到了相同的错误。

这是错误:

提供的参数与目标的呼叫签名

不匹配

但是,如果我使用编译版本并将其粘贴到控制台中,则可以通过记录"字符串"字符串。

var obj = {
    a: 5,
    b: true,
    c: 'string that says string'
};
function x(someObj) {
    return someObj.c;
}
function func(someObj, x) {
    return x(someObj);
}
console.log(func(obj, x));     //string that says string

我正在使用打字稿操场上的编译器:

https://www.typescriptlang.org/play/index.html

我已经在Stackoverflow上查看了其他问题和答案,但它们似乎与更复杂的角度问题有关,但我不了解它们。

以扩展您的评论,向Andrew Li(应该是什么(正确答案,您实际上将自己锁定在自己创建的角落,过度打败。

通过明确键入所有内容,看起来您可能是额外的安全,但是实际上您提供了额外的空间来让矛盾之处。

有弹性看起来像:

function func (obj: Thing, x): string {
  return x(obj);
}

根据您的版本和设置,它可能工作正常(或抱怨"不隐含任何"(。

您所做的就是提供一种不匹配的类型,因为您只是想提供一个安抚系统的抛售。

我并不是要听起来对抗性或任何东西;我们都对此有罪。但是需要安抚类型的系统使我们一直都很草率。

我认为,看待它的痛苦较低的方式就是这样:

interface Transform<A, B> {
  (x:A):B;
}
interface Thing {
  a: number;
  b: boolean;
  c: string;
}
type ThingC = Transform<Thing, string>;
const x = (obj: Thing) => obj.c;
const func = (obj: Thing, x: ThingC) => x(obj);

const c = func({ a: +!0, b: !0, c: "I work fine." }, x);

如果您要在VScode中加载它,我相信您会对从中获得的类型信息感到惊喜。

类型确实是为了获得方法签名。
当然,如果您想围绕它们进行工具,请随时将类型信息添加到consts:

const obj: Thing = { a: 1, b: true, c: "Yes" };

但这并不是最有益的地方;特别是因为即使obj具有不同的类型,例如OtherThing,即使它也符合Thing的标准,它仍然可以进入xfunc,即使它与之无关,并且对此一无所知。

>

使这是一个更加普遍的情况:

interface Transform<A, B> {
  (x:A):B;
}
interface Apply<A, B> {
  (x:A, f: Transform<A, B>):B;
}
interface Thing {
  a: number;
  b: boolean;
  c: string;
}
const x: Transform<Thing, string> = obj => obj.c;
const f: Apply<Thing, string> = (obj, x) => x(obj);
const c = f({ a: 1, b: true, c: "" }, x);

,如果您犯了任何类型的错误,它将对您大喊大叫,但您还是在调用仍在严格的类型检查的文字的函数。

想要Zany的东西?

const g = <A, B>(o: A, x: Transform<A, B>):B => x(o);
const d = g({ a: 1, b: true, c: "" }, x);

您没有告诉 g 关于它正在处理的类型的任何东西。这是一个匿名函数,具有匿名类型,它是转换的。

it still 知道将哪种类型返回到d中,并且它 still 知道oThing(无论其是什么类别或它具有什么界面(。它知道这一点,因为它从 x中拉出了这些类型并向后工作。

所以您有:

interface Transform<A, B> { (x:A):B; }
interface Thing { a: number; b: boolean; c: string; }
const x = (obj: Thing) =>
  obj.c;
const g = <A, B>(o: A, x: Transform<A, B>):B =>
  x(o);
const d = g({ a: 1, b: true, c: "" }, x);

ant 仍然获取d。使用这种类型似乎对您来说是违反直觉的,但是实际上,您可以通过依靠类型推理的优势来对自己的好处,而不是手动使类型系统对额外的噪音感到满意这可能与认为应该拥有的东西相抵触。

相关内容

最新更新