json TypeScript如何为一个接口设置信息,该接口被另一个接口引用

ezykj2lf  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(271)

下面是我用来更新基本地址保持接口的代码。我在访问Park接口中引用的Address接口时遇到问题。为什么我创建的构造函数会出现问题,用信息的地址更新Address接口?

interface Park {
    name: string;
    image: string;
    address: Address;

}
interface Address {
    street: string;
    city: string;
    state: string;
    zip: string;
}

class ArkEncounter implements Park {
    name: string;
    image: string;
    address: Address;

    setName(name: string) {
        this.name = name;
    }
    setImage(image: string) {
        this.image = image;
    }
    setAddress(address: Address) {
        this.address = address;
    }
    getName(): string {
        return this.name;
    }
    getImage(): string {
        return this.image;
    }
    getAddress(): Address {
        return this.address;
    }

    constructor(name: string, image: string, address: Address) {
        this.name = name;
        this.image = image;
        this.address = address;
    }

    printInfo() {
        console.log(`The ${this.name} is located at ${this.address.street}, ${this.address.city}     ${this.address.zip}`);
    }
}

let ArkPark = new ArkEncounter('Ark Encounter', 'https://assets.answersingenesis.org/img/cms/content/contentnode/og_image/ark-encounter-aerial2020.jpg', '1 Ark Encounter Dr, Willianstown, KY 41097');

我希望这种格式能改变Address接口,但我不确定在调用构造函数时实现它的正确方法。

mrfwxfqh

mrfwxfqh1#

ArkEncounter的第三个构造函数参数是Addressinterface,对象类型定义为

interface Address {
    street: string;
    city: string;
    state: string;
    zip: string;
}

这意味着一个Address应该是一个(至少)有四个命名属性的对象,每个属性的类型都是string。像'1 Ark Encounter Dr, Willianstown, KY 41097'这样的string不起作用,因为字符串没有任何这些属性。这就是为什么你得到一个错误。
但是如果你想要一个对象,你可以很容易地创建一个。JavaScript和TypeScript支持object literals,让您可以轻松创建和初始化对象。这里有一个方法:

const implausibleFloatingMenagerieAddress: Address = {
  street: '1 Ark Encounter Dr',
  city: "Willianstown",
  state: "KY",
  zip: "41097"
};

请注意,我将implausibleFloatingMenagerieAddress变量注解为Address类型,但这不是必需的。如果不使用注解,编译器将推断出一个与Address等效的类型:

const implausibleFloatingMenagerieAddress = {
  street: '1 Ark Encounter Dr',
  city: "Willianstown",
  state: "KY",
  zip: "41097"
};

// inferred as type:
/* const implausibleFloatingMenagerieAddress: {
    street: string;
    city: string;
    state: string;
    zip: string;
} */

无论哪种方式,你都可以将其传递到ArkEncounter构造函数中,而不会出现错误:

let arkPark = new ArkEncounter(
  'Ark Encounter',
  'https://assets.answersingenesis.org/img/cms/'
  + 'content/contentnode/og_image/ark-encounter-aerial2020.jpg',
  implausibleFloatingMenagerieAddress
); // okay

或者,如果你愿意,你可以直接使用对象字面量,而不先将其赋值给变量:

let arkPark = new ArkEncounter(
  'Ark Encounter',
  'https://assets.answersingenesis.org/img/cms/'
  + 'content/contentnode/og_image/ark-encounter-aerial2020.jpg',
  {
    street: '1 Ark Encounter Dr',
    city: "Willianstown",
    state: "KY",
    zip: "41097"
  }
); // okay

对象类型是JavaScript和TypeScript如何工作的基础,所以如果你还没有,我建议你通读the TypeScript Handbook
Playground链接到代码

相关问题