对象类型

Tutorial: TS初级一 Category: TS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
  1. 对象类型的声明
let person: {
  name: string;
  age: number;
  greet(name: string): void;
  sayHi: () => void;
} = {
  name: "tom",
  age: 18,
  greet(name) {
    console.log(`Hello, ${name}`);
  },
  sayHi() {
    console.log("hi");
  },
};
console.log(person);
person.greet("ts");
person.sayHi();

// 可选参数
function myAxios(config: { url: string; method?: string }): void {
  config.method = config.method === undefined ? "get" : config.method;
  console.log(config);
}
myAxios({
  url: "www.baidu.com/api/v1/name",
});
Prev: 函数 Next: 接口