微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法在TypeScript中将多种类型的数据放入数组中?

如何解决有没有办法在TypeScript中将多种类型的数据放入数组中?

这是我要问的一个例子。
假设我们有两个接口,UTF-8Cats。我该如何制作一个既可以容纳Dogs也可以容纳Cats的数组?

Dogs

变量interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cats = { name: "Jimmy",age: 5,} const dog1: Dogs = { owner: "Bobby",} // The line below doesn't work how I think it would work const animalsList: Array<Cats> | Array<Dogs> = [cat1,dog1]; 应该可以同时包含animalsListCats,但出现类似
错误 “无法将类型Dogs分配为类型Dogs

解决方法

如果我正确阅读了此问题,则希望能够制作一个既可以容纳猫又可以容纳狗的阵列。它们以目前的方式Array<Cats> | Array<Dogs>表示您可以具有a)仅可容纳Cats的数组,或b)仅可容纳Dogs的数组。

要解决此问题,您需要具有一个可以容纳两者的数组。做到这一点的方法如下:

public animalsList: Array<Cats | Dogs>;

管道的新位置(|)表明此数组是可以同时容纳Cat和Dog的数组。

,

这里是完整样本:

// Welcome to the TypeScript Playground,this is a website
// which gives you a chance to write,share and learn TypeScript.

// You could think of it in three ways:
//
//  - A place to learn TypeScript in a place where nothing can break
//  - A place to experiment with TypeScript syntax,and share the URLs with others
//  - A sandbox to experiment with different compiler features of TypeScript

const anExampleVariable = "Hello World"
console.log(anExampleVariable)

// To learn more about the language,click above in "Examples" or "What's New".
// Otherwise,get started by removing these comments and the world is your playground.
  
class Cats {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am cat ${this.name}`); }
}
class Dogs {
    private name: String;
    constructor(name: String) {
        this.name = name;
    }
    public dump() { console.log(`I am dog ${this.name}`); }
}

class Test {
    public animalsList : Array<Cats> | Array<Dogs> = Array();
}

const t = new Test();
t.animalsList = Array(new Cats('cat1'),new Cats('cat2'));
t.animalsList.forEach((v,i) => { v.dump(); });

t.animalsList = Array(new Dogs('pluto'),new Dogs('goofy'));
t.animalsList.forEach((v,i) => { v.dump(); });

// The following line fails
//t.animalsList = Array(new Dogs('pluto'),new Cats('cat2'));
//t.animalsList.forEach((v,i) => { v.dump(); });

您可以在https://www.typescriptlang.org/play

上尝试

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。