Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typeScript对象类型定义 #4

Open
zhuzhengwen opened this issue Jan 4, 2025 · 0 comments
Open

typeScript对象类型定义 #4

zhuzhengwen opened this issue Jan 4, 2025 · 0 comments

Comments

@zhuzhengwen
Copy link
Owner

对象类型

// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
 console.log("The coordinate's x value is " + pt.x);
 console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });

两个属性的类型注释了参数 - x 和 y - 均为 number 型。你可以使用 , 或 ; 来分隔属性,不指定类型就会假定为any类型

可选属性

function printName(obj: { first: string; last?: string }) {
 // ...
}
// Both OK
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });

在函数入参名字后加入? ,相当于定义该属性不是非必须的,类似java的有参构造器。
注意点,如果该属性不存在需要进行undefined判断

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant