我正在使用VS Code,它在使用Typescript时非常有用,因为它告诉您当前的问题不需要传输。我使用的是Typescript和nodeJS,它工作得很好。
我唯一的问题就是所谓的“空/未定义的检查函数”。
参见此示例:
class User {
public someProperty: string | undefined;
// ...
public get canDoSomething() {
return this.someProperty != undefined;
}
}
let myUser: User = ...
这样做很好:
if (
我最近在TypeScript上偶然发现了这种奇怪的行为。在编译期间,只有当期望变量的类型是接口时,如果接口没有强制字段,它才会抱怨过多的属性。链接到TypeScript游乐场#1:
interface IAnimal {
name?: string;
}
class Animal implements IAnimal {
}
var x : IAnimal = { bar: true }; // Object literal may only specify known properties, and 'bar' does not exist in type
我想知道TypeScript中的类型保护,以及当方法签名中只定义了一种类型时是否有必要使用它们。TypeScript文档中的所有示例仅指具有联合类型的情况,例如:
myMethod(argument: string | number) {
if (typeof argument === 'string') { // do my thing }
if (typeof argument === 'number') { // do my thing }
但我见过人们在类型为强类型时使用typeof:
myMethod(argument: string) {
if
JSX工厂:
function h(type: string, _props, ..._children): HTMLElement {
return document.createElement(type); // breakpoint here is hit
}
tsconfig.json:
"jsx": "react",
"jsxFactory": "h"
在.tsx文件中的用法:
const element = <div></div>; // = any
TypeScript似乎没有推断出J
给定以下代码片段
let x = {
name: 'John',
age: 30
}
interface Employee {
name:string,
}
let y:Employee = <Employee>x;
console.log(y); //y still have the age property, why
为什么typescript会忽略这个类型转换,有没有其他的解决方案来只获取这些接口属性?
我希望在下面的代码中有一个类型错误,但是typescript是完全可以的,你能告诉我为什么吗?
export interface Structure {
aaa: string;
}
export function f1(): Structure[] { // OK for typescript, not for me
const result = [].map(certState => {
return {
aaa: 'aaa',
ADDITIONAL_FIELD: 'asdf&
当在TypeScript中使用带有变量键的对象时,我注意到了意外的类型。
给定以下代码
type MyType = {
[x: number] : number
}
const o : MyType = {
0: 1,
}
const a = o[0]; // Return type correctly identified as number
const b = o[1]; // Return type should be undefined and compiler should not allow this
我注意到,当使用变量键的[x: number]语法定义对象类型时,无
有没有办法用Typescript实现这样的功能呢? class Person {
public name: string;
constructor(data:any) {
this = Object.assign(this, data);
}
}
const p = new Person({name: "Daniel", "age": 30, "gender": "M"});
console.log(p.name) //Daniel
console.log(p.age) //undefined
NSwag生成具有如下定义的属性的typescript类:
export class Foo {
id?: number | undefined;
}
我知道?意味着id属性是可选的。我希望这些属性定义实际上与上面的定义相同:
id?: number
id: number | undefined
这些定义之间有什么区别?为什么NSwag会选择第一个?
我正在使用Ionic2 with angular2 and Typescript2创建一个应用程序。应用程序的主要思想是检测用户位置。
由于需要确保这些数据是正确的,我们需要确保用户不会伪造他们的位置。
经过大量搜索,我找到了以下答案-- ,但这个答案对我没有多大帮助,因为这个插件使用javascript而不是typescript,我在使用它时遇到了问题
那么,是否有可能检查或防止用户伪造GPS位置?
我需要在TypeScript中深度克隆一个对象。这应该不是问题,因为像Lodash这样的库为此提供了适当的函数。然而,这些似乎丢弃了类型信息。
> var a = new SomeClass();
> a instanceof SomeClass;
< true
> var b = _.cloneDeep(a);
> b instanceof SomeClass;
< false
有没有一种方法可以在TypeScript中克隆对象,同时保留这些类型信息?
我有一个这样的代码: // Those two come from backend, it cannot be guaranted
// they do not contain additional fields of any type.
interface Foo1 {
name: string;
}
interface Foo2 {
description: string;
}
// This one is mine and should always contain valid types
class Bar {
text: string;
con