我目前正在调试一些库的代码,并且我一生都不理解特定的错误。
这是我正在调试的代码的简化示例:
type Test1Type<V> = object | ((this: V) => object);
function testFnc(x: string, test1Fnc: Test1Type<string>) {
let res;
if (typeof test1Fnc === "function") {
res = test1Fnc.call(x, x);
}
}
Run Code Online (Sandbox Code Playgroud)
在该行中,res = test1Fnc.call(x, x);该术语test1Fnc被标记为错误:
(parameter) test1Fnc: Function | ((this: string) => object)
The 'this' context of type 'Function | ((this: string) => object)' is not assignable to method's 'this' of type '((this: string) => object) & Function'.
Type 'Function' is not assignable to type '((this: …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试通过使用泛型来抽象发出不同的 HTTP 请求。我json_serializale用于生成fromJson()和toJson()方法。
这是一个简单的模型文件:
import 'package:json_annotation/json_annotation.dart';
part 'article.g.dart';
@JsonSerializable()
class Article {
int id = 0;
String title = "";
Article({this.id, this.title});
factory Article.fromJson(Map<String, dynamic> json) =>
_$ArticleFromJson(json);
Map<String, dynamic> toJson() => _$ArticleToJson(this);
}
Run Code Online (Sandbox Code Playgroud)
我有一个需要传递fromJson- 方法的通用类,请参阅:
typedef CreateModelFromJson = dynamic Function(Map<String, dynamic> json);
class HttpGet<Model> {
CreateModelFromJson createModelFromJson;
HttpGet({
this.createModelFromJson,
});
Future<Model> do() async {
// [... make HTTP request and do stuff ...]
return createModelFromJson(jsonData);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,这里是ArticleService:
class …Run Code Online (Sandbox Code Playgroud)