有谁知道如何使用TypeScript进行投射?
我正在尝试这样做:
var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误:
Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList
Run Code Online (Sandbox Code Playgroud)
除非我将它转换为正确的类型,否则我无法访问脚本元素的'type'成员,但我不知道如何执行此操作.我搜索了文档和样本,但我找不到任何东西.
我使用TypeScript版本2作为Angular 2组件代码.
我收到错误"属性'值'在类型'EventTarget'上不存在"下面的代码,可能是解决方案.谢谢!
e.target.value.match(/\S +/g)|| []).长度
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'text-editor',
template: `
<textarea (keyup)="emitWordCount($event)"></textarea>
`
})
export class TextEditorComponent {
@Output() countUpdate = new EventEmitter<number>();
emitWordCount(e: Event) {
this.countUpdate.emit(
(e.target.value.match(/\S+/g) || []).length);
}
}
Run Code Online (Sandbox Code Playgroud) 我写了这段代码
interface Foo {
abcdef: number;
}
let x: Foo | string;
if (x instanceof Foo) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是TypeScript给了我这个错误:
'Foo' only refers to a type, but is being used as a value here.
Run Code Online (Sandbox Code Playgroud)
为什么会这样?我认为instanceof可以检查我的值是否具有给定类型,但TypeScript似乎不喜欢这样.
我试图在HTML输入文本框中设置值,该文本框是ComponentA打字稿代码的一部分,该代码是代码的一部分ComponentB.
从这个 SO中获取线索我尝试做:
(<HTMLInputElement>document.getElementById("name")).value = response.name;
Run Code Online (Sandbox Code Playgroud)
但这不起作用.还有什么我需要照顾的吗?
编辑:具有Id的元素"name"在ComponentA中,并且试图操纵该元素的上述代码在ComponentB中
这应该是非常基本的,但我无法通过它.
我有一个类:
class MyObject {
value: number;
unit: string;
constructor(value: number, unit: string){
this.value = value;
this.unit = unit;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在HTML中,
<input id="myValue" type="number"></input>
<input id="myUnit" type="text"></input>
Run Code Online (Sandbox Code Playgroud)
我想使用myValue和myUnit创建一个"MyObject"类的Object.我怎么做 ?
就像是:
var value = document.getElementById("myValue");
var unit = document.getElementById("myUnit");
myObject: MyObject = new MyObject(value, unit);
Run Code Online (Sandbox Code Playgroud)
无法以上述方式执行此操作.有什么方法可以解决这个问题?
我们为什么使用:
(document.getElementById("ipv") as HTMLInputElement).value;
Run Code Online (Sandbox Code Playgroud)
代替:
document.getElementById("ipv").value;
Run Code Online (Sandbox Code Playgroud)
?
所以 - 我有一组数据,如下所示:
people = [
{
name: "Bob",
age: "27",
occupation: "Painter"
},
{
name: "Barry",
age: "35",
occupation: "Shop Assistant"
},
{
name: "Marvin",
age: "42",
occupation: "Mechanic"
},
{
name: "Arthur dent",
age: "27",
occupation: "Human"
},
Run Code Online (Sandbox Code Playgroud)
然后我的 html 中也有一个下拉菜单,如下所示 -
people = [
{
name: "Bob",
age: "27",
occupation: "Painter"
},
{
name: "Barry",
age: "35",
occupation: "Shop Assistant"
},
{
name: "Marvin",
age: "42",
occupation: "Mechanic"
},
{
name: "Arthur dent",
age: "27",
occupation: "Human" …Run Code Online (Sandbox Code Playgroud)