简体   繁体   English

在Typescript中为`this`关键字键入注释

[英]Type annotation for `this` keyword in Typescript

I have a standalone function that's meant to use the context provided by Function.prototype.call . 我有一个独立的函数,它意味着使用Function.prototype.call提供的上下文。

For example: 例如:

function foo () {
    return this.bar;
}

> foo.call({bar: "baz"})
baz

Is there a way to provide a Typescript type annotation for the this keyword in this scenario? 有没有办法在此场景中为this关键字提供Typescript类型注释?

It's a bit ugly, in my opinion. 在我看来,它有点难看。

First of all, you can use the special this parameter syntax to identify the type of object you expect this to be: 首先,你可以使用特殊this参数的语法来识别你所期望的对象类型this是:

function foo (this: {bar: string}) {
    return this.bar; // no more error
}

which helps if you call it directly: 如果直接调用它会有帮助:

foo(); // error, this is undefined, not {bar: string}

var barHaver = { bar: "hello", doFoo: foo };
barHaver.doFoo(); // acceptable, since barHaver.bar is a string

var carHaver = { car: "hello", doFoo: foo };
carHaver.doFoo(); // unacceptable, carHaver.bar is undefined

But you want to use foo.call() . 但是你想使用foo.call() Unfortunately the Function.prototype.call() typing in TypeScript won't really enforce this restriction for you: 不幸的是,在TypeScript中键入的Function.prototype.call()不会真正为您强制执行此限制:

foo.call({ bar: "baz" }); // okay, but
foo.call({ baz: "quux" }); // no error, too bad!

Merging something better into TypeScript's Function declaration caused me problems, (First point of ugliness; you will need to cast foo to something) so you can try something like this: 将更好的东西合并到TypeScript的Function声明中会给我带来问题,(丑陋的第一点;你需要将foo为某些东西)所以你可以尝试这样的东西:

interface ThisFunction<T extends {} = {}, R extends any = any, A extends any = any> {
  (this: T, ...args: A[]): R;
  call(thisArg: T, ...args: A[]): R;
}

A ThisFunction<T,R,A> is a function with a this of type T , a return value of type R , and a rest argument of type A[] . ThisFunction<T,R,A>是具有一个功能this类型的T ,类型的返回值R和类型的其余参数A[] (Second point of ugliness: you can't easily specify multiple arguments of different types in a way that will be enforced by the type system.) (第二点丑陋:你不能以类型系统强制执行的方式轻松指定不同类型的多个参数。)

You can then cast foo to ThisFunction<{ bar: string }, string> , (Third point of ugliness: the type system just will not infer this types) and then finally use call() : 然后你可以将fooThisFunction<{ bar: string }, string> ,(第三点丑陋:类型系统不会推断出this类型)然后最后使用call()

(<ThisFunction<{ bar: string }, string>>foo).call({ bar: "baz" }); // okay, and
(<ThisFunction<{ bar: string }, string>>foo).call({ baz: "quux" }); // error, hooray!

Hope that helps! 希望有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM