我正在尝试将一些java库“翻译”成打字稿。
public interface Expression<T> {
<R,C> R accept(Visitor<R,C> v, @Nullable C context);
}
public interface Constant<T> extends Expression<T> {
T getConstant();
}
public interface Visitor<R,C> {
R visit(Constant<?> expr, @Nullable C context);
}
到目前为止,我已经能够编码这段代码了:
interface Expression<T> {
accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
() : T;
}
public interface Visitor<R,C> {
(expr: Constant<any>, context: C): R; //<<<<?>>>>
}
我不确定如何翻译java Constant<?>
。到目前为止,我已将其翻译为Constant<any>
。
这是对的吗?
[编辑]
Interface<? super T>
和Interface<? extends T>
呢?
答案 0 :(得分:2)
因为常量from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
return render_template('user-input.html')
@app.route('/user_input',methods = ['POST'])
def result():
NAME = request.form['Book_Name']
PAGE = request.form['Page']
TEXT = request.form['Text']
TOPIC = request.form['Topic']
pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
return jsonify(pythonDictionary )
的泛型参数没有出现在T
接口定义中的任何地方,我猜想什么都不知道,不需要任何东西 - 没有方法,没有属性 - 来自该类型。在这种情况下,空对象类型Visitor
就足够了 - 它可以从几乎任何其他类型分配。
{}
<强>更新强>
与java类似,TypeScript支持generic type parameter constraints。很难发明一个现实但简单的例子,其中约束是非常必要的,所以这里有愚蠢的例子:
interface Expression<T> {
accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
() : T;
}
interface Visitor<R,C> {
(expr: Constant<{}>, context: C): R;
}
但是,与java不同,typescript没有通配符通用参数 - interface Writer {
write(data: string): void;
}
interface WriterProvider<W extends Writer> {
getWriter(): W;
}
class C<W extends Writer> {
writer: W;
constructor(writerProvider: WriterProvider<W>) {
this.writer = writerProvider.getWriter();
}
writeAll(): void {
this.writer.write('a'); // here we can use its write() method
}
// supposedly something here should take advantage
// of knowing exact W type, as opposed to Writer, at compile time
}
和Interface<? super T>
没有等价物。无法将此类代码直接转换为TypeScript - 您必须使用TypeScript惯用法,并根据具体情况找出表达所需内容的最佳方式。
Java generic FAQ说明了通配符are necessary in situations where no or only partial knowledge about the type argument of a parameterized type is required。
TypeScript has structural type system。这意味着只要对类型的属性或方法有任何了解,您就可以在知识充分的情况下立即使用它。在实践中,没有必要向编译器声明您作为实际泛型参数传递的具体类型符合某些接口或约束 - 它自然地带有结构类型,并且编译器能够自己解决它。