我有一个以svg html元素(<svg></svg>
)为参数的打字稿类:
export class MyClass extends Base {
private svg: SVGSVGElement;
constructor(svg: SVGSVGElement) {
}
}
您将使用javascript这样调用它:
new MyClass(document.getElementById("mySVGElement"));
问题是,如果我传递的不是svg元素,则什么也不会发生。如果传递的html元素不是svg,如何抛出错误?喜欢:
constructor(svg: SVGSVGElement) {
if (svg not svg) {
//throw error
}
}
答案 0 :(得分:2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-78-0358d9976c72> in <module>
----> 1 gv.Polygons(gdf, kdims=['year'], vdims=['pre_anom']).opts(width=600, height=600, tools=['hover'],
2 colorbar=True, cmap='RdBu', color_index='pre_anom',
3 symmetric=True, toolbar='above', line_color='white')
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/geoviews/element/geo.py in __init__(self, data, kdims, vdims, **kwargs)
98 elif isinstance(data, _Element):
99 kwargs['crs'] = data.crs
--> 100 super(_Element, self).__init__(data, kdims=kdims, vdims=vdims, **kwargs)
101
102
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/holoviews/element/path.py in __init__(self, data, kdims, vdims, **params)
217 else:
218 params['vdims'] = vdims
--> 219 super(Contours, self).__init__(data, kdims=kdims, **params)
220 if params.get('level') is not None:
221 with disable_constant(self):
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/holoviews/element/path.py in __init__(self, data, kdims, vdims, **params)
90
91 super(Path, self).__init__(data, kdims=kdims, vdims=vdims,
---> 92 datatype=datatype, **params)
93
94
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/holoviews/core/data/__init__.py in __init__(self, data, kdims, vdims, **kwargs)
210 datatype=kwargs.get('datatype'))
211 (data, self.interface, dims, extra_kws) = initialized
--> 212 super(Dataset, self).__init__(data, **dict(kwargs, **dict(dims, **extra_kws)))
213 self.interface.validate(self, validate_vdims)
214
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/holoviews/core/dimension.py in __init__(self, data, kdims, vdims, **params)
994 params['cdims'] = {d if isinstance(d, Dimension) else Dimension(d): val
995 for d, val in params['cdims'].items()}
--> 996 super(Dimensioned, self).__init__(data, **params)
997 self.ndims = len(self.kdims)
998 cdims = [(d.name, val) for d, val in self.cdims.items()]
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/holoviews/core/dimension.py in __init__(self, data, id, plot_id, **params)
650 params['group'] = long_name
651
--> 652 super(LabelledData, self).__init__(**params)
653 if not util.group_sanitizer.allowable(self.group):
654 raise ValueError("Supplied group %r contains invalid characters." %
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/param/parameterized.py in __init__(self, **params)
2029 self.param._generate_name()
2030
-> 2031 self.param._setup_params(**params)
2032 object_count += 1
2033
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/param/parameterized.py in override_initialization(self_, *args, **kw)
808 original_initialized=parameterized_instance.initialized
809 parameterized_instance.initialized=False
--> 810 fn(parameterized_instance,*args,**kw)
811 parameterized_instance.initialized=original_initialized
812 return override_initialization
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/param/parameterized.py in _setup_params(self_, **params)
950 self.param.warning("Setting non-parameter attribute %s=%s using a mechanism intended only for parameters",name,val)
951 # i.e. if not desc it's setting an attribute in __dict__, not a Parameter
--> 952 setattr(self,name,val)
953
954 @classmethod
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/param/__init__.py in __set__(self, obj, val)
1217 def __set__(self,obj,val):
1218 """Set to the given value, raising an exception if out of bounds."""
-> 1219 self._check_bounds(val)
1220 super(List,self).__set__(obj,val)
1221
~/.conda/envs/anaconda3.6/lib/python3.6/site-packages/param/__init__.py in _check_bounds(self, val)
1236 if min_length is not None and max_length is not None:
1237 if not (min_length <= l <= max_length):
-> 1238 raise ValueError("%s: list length must be between %s and %s (inclusive)"%(self._attrib_name,min_length,max_length))
1239 elif min_length is not None:
1240 if not min_length <= l:
ValueError: kdims: list length must be between 2 and 2 (inclusive)
是上课的权利吗?
SVGSVGElement
答案 1 :(得分:2)
在打字稿中,document.getElementById
返回HTMLElement | null
(请参阅here),并且无法将HTMLElement
转换为SVGSVGElement
(请参阅here并搜索“ HTMLElement”)。
这意味着您必须“假设”构造函数参数内的正确类型,并“检查”构造函数体内的正确性。
export class MyClass extends Base {
private svg: SVGSVGElement;
constructor(svg: SVGSVGElement) {
if (svg instanceof SVGSVGElement === false) {
throw Error()
}
// ...
}
}
关于更改document.getElementById
here的行为,人们进行了积极的讨论。
答案 2 :(得分:0)
您可以将参数类型设置为'any',然后检查svgsvgelement。
虽然可能不是最好的方法。
答案 3 :(得分:0)
您可以使用file.type检查文件的MIME类型
https://developer.mozilla.org/en-US/docs/Web/API/File/type
您可以像这样简单地进行支票
if (!file.type == "image/svg+xml"){
throw new Error('FileType is invalid');
}
答案 4 :(得分:0)
new MyClass(document.getElementById("mySVGElement"));
应引起编译器错误,因为Document.getElementById
返回HTMLElement
。因此,您在编译时已经具有类型安全性。但是,如果仍然需要在运行时强制执行此操作,那么Stefan's answer应该是在运行时进行检查的规范方法。
答案 5 :(得分:0)
export class MyClass extends Base {
constructor(svg: SVGSVGElement) {
if (svg instanceof SVGElement !== true) {
throw new Error('Invalid element passed to constructor!')
}
}
}
这就是stefan-wullems所谈论的代码。