typescript - 具有特定“this”对象的函数的类型定义
问题描述
我想创建一系列如下所示的对象:
type MyThing<T> = {
data: T;
fn: ???;
}
const foo = {
data: {
foo: "bar"
},
fn: function() {
return `Hello ${this.data.foo}!`;
}
}
为了使它起作用,您必须使用长格式function
语法而不是箭头函数。
如果有人要使用箭头函数,我将如何键入此函数以导致错误?
解决方案
您使用特殊参数键入this
arg this: SomeType
。
type MyThing<T> = {
data: T;
fn: (this: MyThing<T>) => void;
}
const foo = {
data: {
foo: "bar"
},
fn: () => {
return `Hello ${this.data.foo}!`;
// The containing arrow function captures the global value of 'this'.(7041)
// Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.(7017)
}
}
推荐阅读
- laravel - 从作业中发送 Guzzle http 请求后没有响应
- reactjs - redux-persist 和 AsyncStorage 有什么区别?
- java - Java,将相同的对象映射到不同的对象
- android - 类似 Snapchat 的 Viewpager 动画
- php - Laravel 在模型中定义多个外键并出现错误
- swift - 类型开关模式
- python - 如何从包含分页的网站中提取链接?(使用硒)
- php - Laravel 5.6 - 验证后表单未重新填充以前的值
- javascript - 在nl2br中使用table标签时如何避免不必要的br标签?
- swift - 在 swift 4.0 中使用枚举下标数组