赞
踩
在typescript开发中我经常遇到一些JSON对象声明,在传参的过程中,对象经常会缺失参数或者参数未定义导致编译失败,在对象声明时我应该注意什么
在 TypeScript 开发过程中,对象声明是非常常见的,下面我们列举一些在对象声明时需要注意的地方:
?
来表示这个属性是可选的。- interface Person {
- name: string;
- age?: number;
- gender?: string;
- }
?
来表示该属性是可选的,或者直接赋值为 undefined。- interface Person {
- name: string;
- age?: number;
- gender?: string;
- address: string | undefined; // 错误的写法
- }
-
- interface Person {
- name: string;
- age?: number;
- gender?: string;
- address?: string;
- }
- interface Person {
- name: string;
- age: number;
- gender: string;
- }
-
- function getInfo(person: Person) {
- console.log(`${person.name}, ${person.age}, ${person.gender}`);
- }
-
- getInfo({ name: 'Tom', age: 18 }); // 缺失 gender 属性导致编译错误
-
- interface Person {
- name: string;
- age: number;
- gender?: string;
- }
-
- function getInfo(person: Person) {
- const { name = '', age = 0, gender = '' } = person;
- console.log(`${name}, ${age}, ${gender}`);
- }
-
- getInfo({ name: 'Tom', age: 18 }); // 缺失 gender 属性不编译错误了

以上是在 TypeScript 开发中对象声明需要注意的一些细节,开发者们在使用 TypeScript 时如果注意一些这些细节可以更加方便和高效地使用该语言
你可以将接口 Example
中的 foo
属性改为可选属性,从而实现 foo
可选的效果,如下所示:
- interface Example {
- foo?(x: string, y: number): string;
- foo?(x: string, y: number, z: boolean): string[];
- }
在接口定义中,我们使用 ?
符号将 foo
属性变为可选属性。
接下来,你可以针对可选的 foo
属性,进行各种调用,如下所示:
- const example: Example = {};
- console.log(example.foo); // undefined
-
- example.foo = (x: string, y: number, z?: boolean): string | string[] => {
- if (z) {
- return [x, y.toString(), z.toString()];
- }
- return x + y.toString();
- };
-
- console.log(example.foo('Hello, ', 42)); // 'Hello, 42'
- console.log(example.foo('World!', 100, true)); // ['World!', '100', true]
在上述代码中,我们首先创建一个空对象 example
,并打印出该对象的 foo
属性,发现它是 undefined。
然后,我们将实现函数赋值给该对象的 foo
属性,这里需要使用一个函数表达式,并根据函数重载的定义,定义了三个参数:x
、y
和可选的 z
。在函数内部,我们按照重载的定义,进行了参数和返回值的处理。
最后,我们通过 example.foo
方法进行了不同的调用,得到了正确的结果。由于 foo
属性为可选属性,在对象实例化时可以不提供该属性,我们可以在后面定义时动态添加该属性,也可以在代码中判断该属性是否存在。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。