This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Preface 🎉

  • Although I have learned TS before, I still use it in ordinary businessJavaScriptTo develop leads gradually onTypeScriptOut of practice.
  • Take this opportunity to study together againTypeScriptKnowledge of.
  • This article isTypeScriptThis is the last part of the foundation, and I will share the knowledge of the advanced part.

Type assertion 🌭

  • Type assertions can be used to manually specify the type of a value.
  • Type assertions are commonly usedasTo connect, i.evalue astype.

The assertion is a type of the union type 🥙

  • When do we usually need to use assertions? We mentioned earlier that the union type:
let someThing: string | number; someThing = 'lwj'; someThing = 5201314; The console. The log (someThing. Length) / / an errorCopy the code
  • The last in the code abovesomeThing.lengthIt can’t be implemented becauseTypeScripIs, in fact,'Not sure'When the value is of what type, so an error is reported, we can use type assertion.
interface Student { name: string; speak(): string; } interface Teacher { name: string; talk(): string; } function isTeacher (people: Student | the Teacher) {. People talk () / / an error (people as the Teacher). Talk () / / no error return false. }Copy the code
  • As defined above, two interfaces have the same properties and different methods when we executepeople.talk()In fact,TypeScripDo not know if the value belongs toStudentorTeacherSo it will naturally report an error, but when we use the type assertion, this is equivalent to tellingTypeScripthispeopleisTeacherType, of course, will not report an error.
  • But there are downsides to using type assertions, such as
interface Student { name: string; speak(): void; } interface Teacher { name: string; talk(): void; } function isTeacher (people: Student | the Teacher) {(people as the Teacher). Talk () / / no error return false. } const man:Student={name:' LWJ ', speak(){console.log(' compiler not error ')}} isTeacher(man) //Copy the code
  • In the example above we giveisTeacherThe function is passed onemanObject, this object does not havetalkMethod, but when we runisTeacherWhen we assert that this parameter isTeacherType, which is that we asserted that this parameter will havetalkMethod, so the compiler trusts us not to report an error, but in factmanThe object is nottalkMethod so finally convert tojsAn error will be reported during compilation.

The assertion is any (any) 🥘

  • inTypeScriptWe usually useobject . Attribute or methodTo get properties or execute methods.
  • We are inJavaScriptCan also be used directlyobject . Attribute or methodTo add a property or method, but such operations inTypeScriptIs not allowed.

  • As shown above we want to givewindowAdd a new objectnumAttribute values for1, which will report an error, so we canwindowAssertion isany.
(window as any).num = 1; / / is not an errorCopy the code
  • Even if the assertion can be so, but it is the last thing we have to do, we use itTypeScriptWe need to use strict type specifications to regulate our projects.

Restrictions on type assertions 🌮

  • TypeScriptIs a structure type system. Comparisons between types only compare their final structure, ignoring their defined relationships.
  • inTypeScriptNot all types can be asserted as another type, and a condition must be met for a type to be assertedCompatible with.
  • Compatible withIt’s not particularly hard to understand.
interface Student {
    name: string;
}
interface Teacher {
    name: string;
    talk(): void;
}

function testpeople(teacher: Teacher) {
    return (teacher as Student);
}
function people(student: Student) {
    return (student as Teacher);
}
Copy the code
  • The first one in the code aboveteacher as StudentThere’s no error becauseTeacherYou can actually interpret it as inheritanceStudentAnd then added a new onetalk()So to this extentTeacherIs compatible withStudent.
  • And the secondstudent as TeacherThere’s no error becauseTeacherHave all theStudentProperties and methods, as if he hadnameProperty, so to this extentStudentIs compatible withTeacher.
  • So to determine whether two types are compatible, we just need to see whether the properties and methods of one type are in the other type, and if so, they are compatible, and we can use assertions.

Put it at the end 👋

  • This is for the recordTypeScriptI will continue to outputTypeScriptRelated knowledge, you can learn together.
  • If you think this article is helpful to your words might as well 🍉 attention + thumbs up + favorites + comments + forwarding 🍉 support yo ~~😛

Past highlights 🌅

Getting Started with TypeScript basics (part 1)🎯

Getting Started with TypeScript basics (2)🎯

Getting Started with TypeScript basics (3)🎯