Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

typescript - How to prevent assiging similar types?

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

Consider following classes:

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();
 }
}

Following works:

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 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();
}

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...