在TypeScript类中,可以为属性声明类型,例如:
class className {
property: string;
};
如何在对象文字中声明属性的类型?
我已经尝试了以下代码,但它不能编译:
var obj = {
property: string;
};
我得到以下错误:
名称“string”在当前作用域中不存在
是我做错了什么还是这是个bug?
在TypeScript类中,可以为属性声明类型,例如:
class className {
property: string;
};
如何在对象文字中声明属性的类型?
我已经尝试了以下代码,但它不能编译:
var obj = {
property: string;
};
我得到以下错误:
名称“string”在当前作用域中不存在
是我做错了什么还是这是个bug?
当前回答
在TypeScript中,如果我们声明object,那么我们将使用以下语法:
[access modifier] variable name : { /* structure of object */ }
例如:
private Object:{ Key1: string, Key2: number }
其他回答
// Use ..
const Per = {
name: 'HAMZA',
age: 20,
coords: {
tele: '09',
lan: '190'
},
setAge(age: Number): void {
this.age = age;
},
getAge(): Number {
return age;
}
};
const { age, name }: { age: Number; name: String } = Per;
const {
coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;
console.log(Per.getAge());
用DRY将对象文字转换为类型
只做:
const myObject = {
hello: 'how are you',
hey: 'i am fine thank you'
}
type myObjectType = keyof typeof MyObject
完成工作!
在TypeScript中,如果我们声明object,那么我们将使用以下语法:
[access modifier] variable name : { /* structure of object */ }
例如:
private Object:{ Key1: string, Key2: number }
要小心了。这对一些人来说可能是显而易见的,但类型声明:
const foo: TypeName = {}
与as的铸造相比不一样:
const foo = {} as TypeName
尽管有人建议把它用在其他答案上。
例子:
谢谢,类型安全!:
const foo: { [K in 'open' | 'closed']: string } = {}
// ERROR: TS2739: Type '{}' is missing the following properties from type '{ open: string; closed: string; }': open, closed
再见,类型安全!:
const foo = {} as { [K in 'open' | 'closed']: string }
// No error
如果你试图写一个类型注释,语法是:
var x: { property: string; } = { property: 'hello' };
如果你试图写一个对象文字,语法是:
var x = { property: 'hello' };
您的代码试图在值位置使用类型名称。