Foreword: Basic types, function types, and class types in TypeScript all have their JavaScript counterparts. But interface types and type aliases are unique to TypeScript, giving iT the ability to describe complex data structures that JavaScript lacks (JavaScript can only do this through documentation and lots of comments).

Interface Interface type

Interface types allow you to define communication rules within modules, across modules, and across project code.

TypeScript’s typing of objects follows the principles of “Duck typing” or “structural subtyping,” which states that two objects are consistent as long as they have the same structure, attributes, and methods.

function Study(language: {name: string, age:() => number}) {
    console.log(`Program language ${language.name} created ${language.age()}years ago! `)
}

Study({
    name: 'TypeScript'.age: () = > new Date().getFullYear() - 2012
})
Copy the code

Ts2345 error ts2345 error ts2345 error ts2345 error TS2345 error TS2345 error TS2345 error TS2345 This is not an oversight or a bug; this is what we call freshness of object literals. Details are as follows:

// ts(2345) Argument is incompatible with Parameter type. There is no attribute ID
Study({
    id: 2.name: 'Typescript'.age: () = > new Date().getFullYear() - 2012
})

Copy the code

Ts type declarations are easily confused with JS constructs

// js, aliasName type alias
function StudyJavascript({name: aliasName}) {}

//ts type declaration
function StudyTypeScript(Language: {name: string}) {}
Copy the code

Defaultable property

Use property names? Indicates that the property can be default. Example:

interface OptionalInterface {
    name: string, age? :() = > number
}
Copy the code

When properties are used? After modification, the property becomes a combination of the specified type and the undefined type

(() = > number) | undefined;
Copy the code

Since the value may be undefined, we can use type guards or Optional Chain if we need to operate on an object’s properties or methods.

if (typeof OptionalTypeScript.age === 'function') { OptionalTypeScript.age() } OptionalTypeScriot.age? . ()Copy the code

Read-only property

Properties modified with the readonly modifier are readable and not writable. Note that after moving to JavaScript, the readonly modifier is erased (and does not prevent object tampering).

Defining function types

Define only the function type, not the implementation of the function.

In front of the index

You can use the [index name: type] format to constrain the type of an index.

React Props & State, HTMLElement Props

interface LanguageRankInterface {
 [rank: number]: string  // The key value can be of type number
}

let languageRankMap: LanguageRankInterface = {
 1: 'Typescript'.2: 'JavaScript'.worngIndex: '2021' // ts2322
}

interface LanguageYearInterface {
 [name: string]: number
}

let languageMap: LanguageYearInterface {
    Typescript: 2012.javascript: 1995.1: 1970 // ok
}

Copy the code

Note: When a number is used as an object index, her type is compatible with both numbers and strings, which is consistent with JavaScript behavior. Therefore, using 0 or ‘0’ is equivalent

Use readonly for direct index signatures

interface LanguageRankInterface {
    readonly [rank: string]: string;
    age: number; // ts 2411, the age attribute string cannot be assigned to a string index type
}

Copy the code

Note: Although attributes can be mixed with index signatures, the type of the attribute must be itself of the corresponding numeric or string index type, otherwise an error message will appear.

A numeric index attribute cannot be constrained to have a distinct type from a string index attribute.

Interface LanguageRankInterface {[rank: number] : string,Ts 2413, string cannot be assigned to string index number
    [prop: string]: number;
}
Copy the code

TODO: If you need to use the object data structure of age is nunber, and other attribute types are string, how do you define it?

{
    age: 1.otherProperty: 'string'
}
Copy the code

Inheritance and Implementation

Interfaces can inherit from interfaces using the extends keyword, implement them using classes, and represent them using the implements keyword

Inheriting the sample

{
    interface DynamicLanguage extends ProgramLanguage {
        rank: number
    }
    
    interface TypeScriptLanguage extends DynamicLanuage, TypeSafeLanuage {
        name: 'TypeScript'
    }
    
    // Only compatible types can be used to override inherited attributes
    interface WrongTypeLanuage extends ProgramLanuage {
        name: number // ts6196}}Copy the code

Implementation examples

{
    class LanuageClass implements Programlanguage {
        name: string = ' ';
        age = 8}}Copy the code

Type Type alias

One of the functions of the interface type is to pull the inline type out, making the type edible. In fact, we can also use the type alias to receive the extracted inline type. Use the type keyword

{
    type LanuageType = {
        name: string;
        age: () = > number
    }
}
Copy the code

Resolve the scenario where the interface cannot be overwritten

For scenarios that cannot be covered by interface types, such as composite types and cross types, only type aliases can be used to receive.

// Type union
type MixedType = string | number;

/ / cross
type InrersectionType = { id: number; name: string } & { age: number }

// Retrieve the interface attribute type
type AgeType = IntersectionType['age']
Copy the code

Interface and Type

Where interface type annotations are appropriate, type aliases can be used instead. It’s different in some cases.

Interface features

  1. Optional attribute
  2. Read-only property
  3. Redundant attribute check
  4. Function types
  5. The index type
  6. Class types (inheritance, implementation)
interface BaseInterface {
     readonly id: number;
}
interfaceSampleInterface exends BaseInterface { name? :string;
   // (source:string, substing: strign): boolean;
    age: () = > number; [index:string] :number | string | boolean  
}

class demo implements SampleInterface {
 / /...
}
Copy the code

The difference between

  1. The interface is defined repeatedly, and its attributes are superimposed. This allows us to easily extend global variables, third-party library types. Repeat type definition, error (TS2300).
  2. Interfaces can be inherited and implemented, not types (but types can be extended by joining, crossing)
  3. Interfaces have indexed signatures that can be used to constrain classes (without specifying attribute names),
{
    interface Language {
        id: number
    }
    interface Language {
        name: string
    }
    
    let lang: Language {
        id: 1;
        name: 'name'
    }
}
Copy the code