如何防止分配相似类型? [英] How to prevent assiging similar types?

查看:29
本文介绍了如何防止分配相似类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止 TypeScript 允许为声明的变量分配相似但不同的类型?

How do I prevent TypeScript from allowing assigning similar but different types to a declared variable?

考虑以下课程:

class Person {
 private firstName;
 private lastName;

 public setFirstName(firstName: string): void {
  this.firstName = firstName;
 }

 public setLastName(lastName: string): void {
  this.lastName = lastName;
 }

 public getFullName(): string {
  return this.firstName + ' ' + this.lastName;
 }
}

class Man extends Person {
 public getFullName(): string {
  return 'Mr. ' + super.getFullName();
 }
}

class Woman extends Person {
 public getFullName(): string {
  return 'Ms. ' + super.getFullName();
 }
}

以下作品:

var jon: Man = new Woman();
var arya: Woman = new Man();

上述工作的原因是 ManWoman 类型的属性和方法是相似的.如果我添加了 ManWoman 独有的一些属性或方法,它会按预期抛出错误.

The reason for above to work is that properties and methods of both Man and Woman types are similar. If I added some property or method unique to either Man or Woman, it'll throw an error as expected.

如果有人将具有相似签名的不同类型分配给为另一个类型声明的变量,我如何让 TypeScript 抛出错误?

How do I get TypeScript to throw errors if someone assign different types with similar signatures to variables declared for another type?

推荐答案

这是设计使然,如果类型匹配,TypeScript 不会抛出错误.

This is by design, TypeScript won't throw errors if the types match.

TypeScript 的核心原则之一是类型检查关注值的形状".这有时被称为鸭子打字".或结构子类型".

One of TypeScript's core principles is that type-checking focuses on the 'shape' that values have. This is sometimes called "duck typing" or "structural subtyping".

http://www.typescriptlang.org/Handbook#interfaces

因此,这将在运行时进行检查.

As a result, this is something that would be checked at runtime.

var arya: Woman = new Man();

if (arya instanceof Man) {
    throw new Error("Dude looks like a lady! *guitar riff*");
}

TypeScript 理解 instanceof,因此它也可用于转换类型.

TypeScript understands instanceof so it can be used to cast types as well.

var jon: Man = new Woman();

if (jon instanceof Man) {
    // The type of `jon` is Man
    jon.getFullName();
}

if (jon instanceof Woman) {
    // The type of `jon` is Woman
    jon.getFullName();
}

最后,您还可以使用 1.6 中提供的类型保护.

Lastly you can also use type guards available in 1.6.

function isMan(a: Person): a is Man {
    return a.getFullName().indexOf('Mr. ') !== -1;
}

var arya: Woman = new Man();

if(isMan(arya)) {
    // The type of `arya` is Man
    arya.getFullName();
}

这篇关于如何防止分配相似类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆