我有一个独立的函数,它意味着使用Function.prototype.call提供的上下文.
例如:
function foo () {
return this.bar;
}
> foo.call({bar: "baz"})
baz
有没有办法在此场景中为this关键字提供Typescript类型注释?
解决方法:
在我看来,它有点难看.
首先,您可以使用特殊的this
parameter语法来标识您期望的对象类型:
function foo (this: {bar: string}) {
return this.bar; // no more error
}
如果直接调用它会有帮助:
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
但是你想使用foo.call().不幸的是,在TypeScript中键入的Function.prototype.call()不会真正为您强制执行此限制:
foo.call({ bar: "baz" }); // okay, but
foo.call({ baz: "quux" }); // no error, too bad!
将更好的东西合并到TypeScript的函数声明中会给我带来问题,(丑陋的第一点;你需要将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函数< T,R,A>是一个带有T类型的函数,类型为R的返回值,以及类型为A []的rest参数. (第二点丑陋:你不能以类型系统强制执行的方式轻松指定不同类型的多个参数.)
然后你可以将foo转换为ThisFunction< {bar:string},string>,(第三点丑陋:类型系统不会推断出这种类型)然后最后使用call():
(<ThisFunction<{ bar: string }, string>>foo).call({ bar: "baz" }); // okay, and
(<ThisFunction<{ bar: string }, string>>foo).call({ baz: "quux" }); // error, hooray!
希望有所帮助!
原文地址:https://codeday.me/bug/20190828/1751241.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。