Typescript compiler当我尝试使用联合或多种类型/接口时,不断抛出错误。
我的要求
我从服务器收到一个对象作为响应,其中一个键('errorMessages')具有数据类型string[],另一个键('data')可以是 anobject或 an array。我interface为此写了一个应该如下所示的内容:
interface MyServerResponse {
errorMessages: string[];
data: {
headers: string[];
body: any[][];
} | any[]>;
}
Run Code Online (Sandbox Code Playgroud)
尝试访问“标头”时收到编译器错误
属性“headers”在类型“any[] |上不存在” { 标题:字符串[];主体:任意[][];}'
难道不能像 for number | boolean、string | null等一样使用 union 来实现吗?
我有一个包含多个字典变量的类。有没有办法设置类变量的字典参数,其中变量名在函数中作为字符串传递?
<?php
class Test:
var1 = { "value": 1 }
var2 = { "value": 2 }
def set_variable(self, var_name, value):
## self.var_name.value = value ### pylint: Instance of 'Test' has no 'var_name' member
self[var_name]["value"] = value ### pylint: 'self' is unsubscriptable ###
instance = Test()
instance.set_variable("var1", 150)
Run Code Online (Sandbox Code Playgroud)
在编码时,linter 会抛出错误,指出:“‘self’不可订阅”。如果执行代码,我会收到错误:“TypeError:'Test'对象不可下标”。
解决此问题的一种方法是使用“getattr”创建临时变量:
def set_variable(self, var_name, value):
temp = getattr(self, var_name)
temp["value"] = value
setattr(self, var_name, temp)
Run Code Online (Sandbox Code Playgroud)
但是,我发现上面的解决方案增加了内存使用量,特别是对于更大的字典来说是一个丑陋的解决方案。
另外,我想在很多地方使用 self[var_name] 。有没有办法做到这一点?