我正在使用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
为什么整个对象的赋值是有效的,但是属性的重新分配不起作用(除非您使用属性名称作为索引)?这有什么意义吗?
var m: object ;
m = { name: 'qwerty' }; // works
m.name = 'xyz'; // does not work
m["name"] = 'abc'; // works
不过,我不知道何时使用Object、object或{},因为这三种方法只匹配没有任何属性的对象--这些属性非常无用。每当我想要匹配具有未知属性的对象时,我都会引用{ [x:string] any}或
当在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]语法定义对象类型时,无
我可以通过console.log访问redux中的信息。但是当我试图访问这些信息的某些部分时,我会得到一些类型错误。
const profile = useSelector(state => state);
console.log(profile); // Work's and print the info
console.log(profile.auth.token); // Does not work
TypeScript错误在/src/components/Header/index.tsx(17,24):对象的类型‘未知’。
下面是一个以TypeScript的Optional类为松散模型的Optional<T>类。如何修改这个类或创建一个具有类似语义的类,TypeScript将在该类中强制执行,或至少警告在访问.value()之前检查.hasValue
(不希望使用null或undefined作为“缺失”的前哨值,因为这正是该类的目的--以避免使用哨位值,从而可以将“结果为空/未定义”与“没有结果”区分开来。)
export default abstract class Optional<T> {
abstract get hasValue(): boolean
abstract g
这是一个复杂的例子,但我不知道为什么TypeScript没有在这里抛出一个错误。
export class Square {
width: number;
}
export class MyShapeBox<T> {
shape: T;
}
var mySquareBox = new MyShapeBox<Square>();
var rectangle = { width: 3, height: 10 };
// Should this not fail?
mySquareBox.shape = rectangle;
根据我们的讨论,最好的猜
我写TypeScript已经有一段时间了,我对索引签名意味着什么感到困惑。
例如,此代码是合法的:
function fn(obj: { [x: string]: number }) {
let n: number = obj.something;
}
但是,这段代码基本上是一样的,但它不是:
function fn(obj: { [x: string]: number }) {
let p: { something: number } = obj;
}
这是个虫子吗?这意味着什么?
我正在将一个C#桌面应用程序重构为一个棱角/类型记录的web应用程序。
C#应用程序中的所有类属性都使用PascalCase,所以我认为,保留它是个好主意。
下面是两个基本相同的TypeScript类的示例。1号使用PascalCase,2号使用camelCase:
//PascalCase
export class Info
{
public ManagedType:string;
public ApiTemplate:string;
}
//camelCase
export class Info
{
public managedType:string;