After three months of typescript writing, what have I learned?

While you're young 233 2021-05-03 11:26:10
months typescript writing learned


 Yes 3 Months TypeScript, What I learned ?.png

Link to the original text :TypeScript introduction

Read before vue I found that there are TypeScript, A face of meng , So you need a door .

Recently, it also needs to be used in the daily work of the new environment TypeScript, In the process of learning, I met some doubts , I took notes .

I think it's more suitable TypeScript introduction My classmates read , Because of all the doubts I've had , Maybe you'll meet .

  • ts Type in the ?,<> What do you mean ?
  • What is? duck typing?
  • constructor What was the previous definition of variables ?
  • declare What is it? ?
  • ts in unknown, void, null and undefined,never What's the difference ?
  • ts What are the generic constraints in ?
  • Two ways to define array types
  • ts Type assertion in
  • Generic functions and generic interfaces
  • How to understand as const?
  • declare global What does that mean? ?
  • How to be in TypeScript Add a global variable to the environment ?
  • interface Can it be inherited ?
  • typescript Medium & What does that mean? ?
  • interface And type What's the difference ?
  • enum What does it mean to be a type ?
  • In the project xxx.d.ts Of declare module '*.scss' What does that mean? ?declare module What else can be done ?
  • typescript How to constrain Promise The type of ?
  • typescript Medium keyof How to use ?
  • typescript Medium typeof How to use ?
  • typescript Medium non-null operator What is it? ?

ts Type in the ? What do you mean ?

// https://github.com/vuejs/vue/blob/dev/src/core/observer/watcher.js
before: ?Function;
options?: ?Object,
 Copy code 

This is a ts Of interface A concept in .ts Of interface Namely "duck typing" perhaps "structural subtyping", Type checking focuses on the shape that values have. So let's get familiar with interface, Again lead to ? The explanation of .

TypeScript Define functions in a normal way :
function print(obj: {label: string}) {
console.log(obj.label);
}
let foo = {size: 10, label: " This is a foo, 10 Jin "};
print(foo);
 Copy code 
TypeScript interface How to define functions :
interface labelInterface {
label: string;
}
function print(obj: labelInterface) {
console.log(obj.label);
}
let foo = {size: 10, label: " This is a foo, 10 Jin "};
print(foo);
 Copy code 

Get to the point ,TypeScript Medium What does that mean? ?Optional Properties.

Optional Properties
  • Not at all interface All attributes in are required Of , Some exist under certain conditions , Some don't exist at all .
  • Optional Properties Apply to "option bags" Design mode of , This design pattern means : We pass an object to a function , This function has only a few properties , There are no more attributes .
  • Optional Property Is that , Clearly see what the attributes are , Preventing incoming traffic does not belong to interface Properties of .
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
 Copy code 

Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration.

What is? ? and Optional Properties Well ?interface Some of the non required The end of the property name , add to ? This is a optional property, It's literally , Conditional properties .

Optional Property Just the property name , That is to say options?: ?Object, in options The question mark after , Take the question mark before the attribute value type , That is to say ?Object, What does that mean? ? The question mark here represents whether the attribute value type can be null type , But only strictNullChecks by on when , Value type can be null.

 /**
* @type {?number}
* strictNullChecks: true -- number | null
* strictNullChecks: off -- number
* */
var nullable;
 Copy code 

In our example ,options?:?Object It means options The value type of can be Object,null( Only in strictNullChecks by true Time allowed ).

ts Type in the <> What do you mean ?

deps: Array<Dep>a
newDeps: Array<Dep>
 Copy code 

ts The array type in is related to java The definition in is similar to :

let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
 Copy code 

What is? duck typing?

duck test. If " Ducks are like walking , It sounds like a duck , So this is the duck ". stay computer programming, be used for ' Judge whether the object can be used according to the expected purpose '. Usual typing in , Applicability depends on the type.duck typing Dissimilarity , The applicability of objects depends on Appoint method or property The presence or absence , Rather than depending on the type of the object itself .

Front end engineers are basically duck typing, because JavaScript No, type. -- That's what I said

Python3 example
class Duck:
def fly(self):
print("Duck flying")
class Airplane:
def fly(self):
print("Airplane flying")
class Whale:
def swim(self):
print("Whale swimming")
def lift_off(entity):
entity.fly()
duck = Duck()
airplane = Airplane()
whale = Whale()
lift_off(duck) # prints `Duck flying`
lift_off(airplane) # prints `Airplane flying`
lift_off(whale) # Throws the error `'Whale' object has no attribute 'fly'`
 Copy code 
Javascript example
class Duck {
fly() {
console.log("Duck flying")
}
}
class Airplane {
fly() {
console.log("Airplane flying")
}
}
class Whale {
swim() {
console.log("Whale swimming")
}
}
function liftOff(entity) {
entity.fly()
}
const duck = new Duck();
const airplane = new Airplane();
const whale = new Whale();
liftOff(duck); // Duck flying
liftOff(airplane); // Airplane flying
liftOff(whale); // Uncaught TypeError: entity.fly is not a function
 Copy code 

constructor What was the previous definition of variables ?

for example vnode The definition of :

export default class VNode {
tag: string | void;
data: VNodeData | void;
children: ?Array<VNode>;
text: string | void;
elm: Node | void;
ns: string | void;
context: Component | void; // rendered in this component's scope
key: string | number | void;
componentOptions: VNodeComponentOptions | void;
componentInstance: Component | void; // component instance
parent: VNode | void; // component placeholder node
// strictly internal
raw: boolean; // contains raw HTML? (server only)
isStatic: boolean; // hoisted static node
isRootInsert: boolean; // necessary for enter transition check
isComment: boolean; // empty comment placeholder?
isCloned: boolean; // is a cloned node?
isOnce: boolean; // is a v-once node?
asyncFactory: Function | void; // async component factory function
asyncMeta: Object | void;
isAsyncPlaceholder: boolean;
ssrContext: Object | void;
fnContext: Component | void; // real context vm for functional nodes
fnOptions: ?ComponentOptions; // for SSR caching
fnScopeId: ?string; // functional scope id support
constructor ()
...
}
 Copy code 

www.typescriptlang.org/docs/handbo… typeScript Medium class than es6 One more thing :property. This sum java perhaps c# In the same .

property
constructor
method
 Copy code 

actually es6 Provides a private variable , Only in class Internal visits .

class Rectangle {
#height = 0;
#width;
constructor(height, width) {
this.#height = height;
this.#width = width;
}
}
 Copy code 

Behind the colon :VNode What do you mean ?

export function cloneVNode (vnode: VNode): VNode {
...
}
 Copy code 

TypeScript Function return value type in .

declare What is it? ?

Declare that this is a definition.

  • declare yes ts For Write definition file Key words of .
  • declare You can define global variables , Global function , Global namespace ,class wait .
  • declare You can use it as follows :
declare var foo:number;
declare function greet(greeting: string): void;
declare namespace myLib {
function makeGreeting(s: string): string;
let numberOfGreeting: number;
}
declare function getWidget(n: number): Widget;
declare function getWidget(s: string): Widget[];
declare class Greeter {
constructor(greeting: string);
greeting: string;
showGreeting(): void;
}
 Copy code 

ts in any,unknown, void, null and undefined,never What's the difference ?

null,undefined Namely js It means .

any: Any type , Use caution , Avoid making typescript become anyscript unknown: And any similar , But compared to any More secure void: Functions commonly used to return values never:never occur Types that never happen , For example, there will never be a result , Throw an exception or loop .

ts What are the generic constraints in ?

be based on string(boolean, Function) type

function loggingIdentity<T extends string>(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentity("hello"); // 5
loggingIdentity(2); // Argument of type 'number' is not assignable to parameter of type 'string'.
 Copy code 

Custom based interface

interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
loggingIdentity(3); // Error, number doesn't have a .length property
loggingIdentity({length: 10, value: 3}); // 10
 Copy code 

ts2.8 Release notes

// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html
type TypeName<T> = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: T extends undefined
? "undefined"
: T extends Function
? "function"
: "object";
type T0 = TypeName<string>; // "string"
type T1 = TypeName<"a">; // "string"
type T2 = TypeName<true>; // "boolean"
type T3 = TypeName<() => void>; // "function"
type T4 = TypeName<string[]>; // "object"
 Copy code 

Support at the same time type and interface Two types of generic constraints

interface reduxModel<T> {
reducers: T extends string ? {[x in T]: () => void}: T,
}
type TType = "foo" | "bar" | 'baz'
interface TInterface {
"foo": () => void,
"bar": () => void,
'baz': () => void
}
const ireducers = {
"foo": () => void
}
const model : reduxModel<TType> = {
reducers: ireducers
// The normal operation 
}
const model : reduxModel<TInterface> = {
reducers: ireducers
// Type '{ foo: () => undefined; }' is missing the following properties from type 'TInterface': "bar", 'baz'
}
 Copy code 

Two ways to define array types

Array< type >

Array Add one at the end <>,<> Declare element types inside .

type Foo= Array<string>;
 Copy code 
interface Bar {
baz: Array<{
name: string,
age: number,
}>
}
 Copy code 

type []

The element type is followed by a [].

type Foo = string[]
 Copy code 
interface Bar {
baz : {
name: string,
age: number,
}[]
}
 Copy code 

ts Type assertion in

TypeScript Allows us to override the inferred and analyzed view types in any way we want , This mechanism is called type assertion (Type Assertion), A type assertion tells the compiler that you know better than it does which type it is , The compiler doesn't have to infer again . Type assertions often occur during compiler compilation , Used to prompt the compiler how to analyze our code .

  • grammar
  • transfer js Code
  • The problem with type assertion
  • Appoint event type
  • Use with caution as any and as unknown
  • type And type assertion

grammar

interface Foo {
name: string,
}
type Any = any;
let a:Foo = {} as Foo;
let a:Foo = {} as Any;
 Copy code 

any Is a subtype of any type , So any type can be as any, It is recommended to use it with caution , Avoid becoming anyscript.

transfer js Code

var foo = {};
foo.bar = 123; // Error: property 'bar' does not exist on `{}`
foo.bas = 'hello'; // Error: property 'bas' does not exist on `{}`
 Copy code 
interface Foo {
bar: number;
bas: string;
}
var foo = {} as Foo;
foo.bar = 123;
foo.bas = 'hello'; // Comment out this line will not report an error 
 Copy code 

The problem with type assertion

foo.bas = 'hello'; // Comment out this line will not report an error If it is in the following way, it will report an error , Will prompt for missing bas The definition of

interface Foo {
bar: number;
bas: string;
}
var foo : Foo= {
bar: 123
};
 Copy code 

So , Type assertion is not rigorous enough , It is recommended to use var foo : Foo This way, .

Appoint event type

function handler (event: Event) {
let mouseEvent = event as MouseEvent;
}
 Copy code 
function handler(event: Event) {
let element = event as HTMLElement; // HTMLElement It's not a complete event subtypes , So it can't overlap enough , Need to add one unknown perhaps any
}
 Copy code 

The second assertion compilation prompt is cancelled :

function handler(event: Event) {
let element = event as unknown as HTMLElement; // Okay!
}
 Copy code 

Use with caution as any and as unknown

Usually it's type assertion S and T Words ,S by T Subtypes of , perhaps T by S Subtypes of , This is relatively safe . If it is used as any perhaps as unknown, It's very unsafe . Use with caution ! Use with caution !

// Use caution 
as any
as known
 Copy code 

type And type assertion

type keys = 'foo' | 'bar' | 'baz',obj[key as keys] What does that mean? ? And variable:type similar , This is another type constraint .

If you don't understand flowers , After reading the following demo Will understand the .

type keys = 'foo' | 'bar' | 'baz'
const obj = {
foo: 'a',
bar: 'b',
baz: 'c'
}
const test = (key:any) => {
return obj[key] ; // Prompt error type 'any' can't be used to index type '{ foo: string; bar: string; baz: string; }'.
}
 Copy code 

How to solve this problem ? The first way : Type constraint

const test = (key:keys) => {
return obj[key] ;
}
 Copy code 

The second way : Types of assertions ( This method is often used in third-party libraries callback, The return value type is not constrained )

const test = (key:any) => {
return obj[key as keys] ;
}
 Copy code 

We need to pay attention to :obj[key as keys] in keys The type of can be less than obj The type of , In turn, obj The attribute of cannot be less than keys The type of .

Generic functions and generic interfaces

Generic functions

Think of a scene , We want the input and output types of the function to be the same . You might do that , But this doesn't guarantee that the input and output types are the same .

function log(value: any):any {
return value;
}
 Copy code 

It can be precisely realized through generic functions : Add one after the function name <T> there T It can be understood as the name of generics . Specifies that the input type is T, The return value is T.

function log<T>(value: T):T {
return value;
}
 Copy code 

This is an example of a generic function , How to define a generic function type ?

type Log = <T>(value: T) => T
 Copy code 

Use generic function types to constrain functions :

let log : Log = function <T>(value: T):T {
return value;
}
 Copy code 

Generic interface

All properties of the interface are flexible , Input and output are consistent .

interface Log {
<T>(value: T): T
}
let myLog: Log = log
myLog("s")// "s"
myLog(1)// 1
 Copy code 

All properties of an interface must be of the same type .

interface Log<T> {
(value: T): T
}
let myLog: Log<string> = log
myLog("s")// "s"
myLog(1)// Error
 Copy code 

ts Medium <>

stay ts in , encounter <> Words , The middle of the angle brackets is mostly a type .

  • Array<string>
  • <string>[]
  • function <T>(value: T): T { ... }
  • type MyType = <T>(value : T) => T
  • interface MyInterface<T> { (value: T): T }

How to understand as const?

  • In order to solve let The problem of assignment is , Will a mutable Change the variable to readonly.
  • Avoid inferring types as union types .

In order to solve let The problem of assignment is , Will a mutable Change the variable to readonly.

let x = "hello";
x = "world"; // Report errors 
 Copy code 
The first way const
const x = "hello"
 Copy code 
The second way "hello" type
let x: "hello" = "hello";
x = "world"; // 
 Copy code 
The third way discriminated unions
type Shape =
| { kind: "circle", radius: number }
| { kind: "square", sideLength: number }
function getShapes(): readonly Shape[] {
// to avoid widening in the first place.
let result: readonly Shape[] = [
{ kind: "circle", radius: 100, },
{ kind: "square", sideLength: 50, },
];
return result;
}
 Copy code 
The fourth way as const

.tsx Type file

// Type '10'
let x = 10 as const;
// Type 'readonly [10, 20]'
let y = [10, 20] as const;
// Type '{ readonly text: "hello" }'
let z = { text: "hello" } as const;
 Copy code 

Not .tsx Type file

// Type '10'
let x = <const>10;
// Type 'readonly [10, 20]'
let y = <const>[10, 20];
// Type '{ readonly text: "hello" }'
let z = <const>{ text: "hello" };
 Copy code 

Optimize discriminated unions

function getShapes() {
let result = [
{ kind: "circle", radius: 100, },
{ kind: "square", sideLength: 50, },
] as const;
return result;
}
for (const shape of getShapes()) {
// Narrows perfectly!
if (shape.kind === "circle") {
console.log("Circle radius", shape.radius);
}
else {
console.log("Square side length", shape.sideLength);
}
}
 Copy code 

Avoid inferring types as union types .

Avoid inferring the type as (boolean | typeof load)[], It is inferred that [boolean, typeof load].

export function useLoading() {
const [isLoading, setState] = React.useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]
}
 Copy code 

declare global What does that mean? ?

To make a declaration in the global namespace , For example, adding an undefined attribute to an object .

by Window increase csrf The definition of

declare global {
interface Window {
csrf: string;
}
}
 Copy code 

by String increase fancyFormat The definition of

declare global {
/*~ Here, declare things that go in the global namespace, or augment
*~ existing declarations in the global namespace
*/
interface String {
fancyFormat(opts: StringFormatOptions): string;
}
}
 Copy code 

Be careful global Scope can only be used to export modules or external module declarations

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.

How to be in TypeScript Add a global variable to the environment ?

For example, we want to achieve the following effect , But it will report an error Property 'INITIAL_DATA' does not exist

<script>
window.__INITIAL_DATA__ = {
"userID": "536891193569405430"
};
</script>
const initialData = window.__INITIAL_DATA__; // Report errors 
 Copy code 

Use type assertion

const initialData = (window as any).__INITIAL_DATA__;
 Copy code 
type InitialData = {
userID: string;
};
const initialData = (window as any).__INITIAL_DATA__ as InitialData;
const userID = initialData.userID; // Type string
 Copy code 

Declare global variables

declare var __INITIAL_DATA__: InitialData;
 Copy code 
const initialData = __INITIAL_DATA__;
const initialData = window.__INITIAL_DATA__;
 Copy code 

stay es Module , Yes import,export Of , It needs to be done :

export function someExportedFunction() {
// ...
}
declare global {
var __INITIAL_DATA__: InitialData;
}
const initialData = window.__INITIAL_DATA__;
 Copy code 

If it is used in many files , You can use a globals.d.ts file .

utilize interface Merge

interface Window {
__INITIAL_DATA__: InitialData;
}
const initialData = window.__INITIAL_DATA__;
 Copy code 

stay js The module needs to look like this :

export function someExportedFunction() {
// ...
}
declare global {
interface Window {
__INITIAL_DATA__: InitialData;
}
}
const initialData = window.__INITIAL_DATA__;
 Copy code 

interface Can it be inherited ?

Tolerable .

interface Base {
foo: string;
}
interface Props extends Base {
bar: string
baz?: string
}
const test = (props: Props) => {
console.log(props);
}
test({ foo: 'hello' }) // Property 'bar' is missing in type '{ foo: string; }' but required in type 'Props'
test({ foo: 'hello', bar: 'world' })
 Copy code 

When Props Inherited Base after , In fact, it ended up like this :

interface Props extends Base {
foo: string;
bar: string
baz?: string
}
 Copy code 

Props You can override Base Do you ? Sure , But it can only be required Cover optional,optional Can't cover required.

// 
interface Base {
foo?: string;
}
interface Props extends Base {
foo: string;
bar: string
baz?: string
}
 Copy code 
// 
interface Base {
foo: string;
}
interface Props extends Base {
foo?: string;
bar: string
baz?: string
}
 Copy code 

typescript Medium & What does that mean? ?

stay react Of dts There's a definition in the file .

type PropsWithChildren<P> = P & { children?: ReactNode };
 Copy code 

typescript Medium & It's the cross type .

interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
interface ArtistsData {
artists: { name: string }[];
}
// These interfaces are composed to have
// consistent error handling, and their own data.
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
const handleArtistsResponse = (response: ArtistsResponse) => {
if (response.error) {
console.error(response.error.message);
return;
}
console.log(response.artists);
};
 Copy code 

know & yes ts After the cross type in , We understand PropsWithChildren I'm not sure , And understand why react There will be more functional components than ordinary ones children attribute .

It means PropsWithChildren The type is P And the object {children?: ReactNode} The cross type of , That is, through & After connecting two objects , The final object is to have children This optional property is .

interface And type What's the difference ?

An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot. An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

  1. interface Inherit ( For example, use extends),type Can not be
  2. interface You can implement multiple merge declarations ,type Can not be

enum What does it mean to be a type ?

In the reading pixi.js In the source code , There will be enum As a type .

enum It can also be used as a type to constrain .

// pixi/constants
export enum BLEND_MODES {
NORMAL = 0,
ADD = 1,
MULTIPLY = 2,
SCREEN = 3,
OVERLAY = 4,
}
export enum ANOTHER_ENUM {
FOO = 5,
BAR = 6
}
import { BLEND_MODES } from '@pixi/constants';
export class Sprite extends Container
{
public blendMode: BLEND_MODES;
constructor(){
this.blendMode = BLEND_MODES.NORMAL; // The best 
// this.blendMode = 0 This is OK , second 
// this.blendMode = ANOTHER_ENUM.FOO such ts Will report a mistake 
}
}
 Copy code 

In the project xxx.d.ts Of declare module '*.scss' What does that mean? ?declare module What else can be done ?

In the project xxx.d.ts Of declare module '*.scss' What does that mean? ?

// externals.d.ts
declare module '*.scss'
 Copy code 

By default import style from 'style.scss' stay ts Of ide An error will be reported in the calibrator , Then use d.ts Suppose we define all scss The document at the end is module.-- President

Assume that declare module '*.scss' Comment out ,ide Will report a mistake , But it can go through lint.

declare module What else can be done ?

When we introduced a Microsoft official @types/* When a custom package does not exist in ,ide Will report a mistake .

Like the following : image

How to solve this problem ?declare module

// typing.d.ts
declare module 'visual-array'
 Copy code 

So the red is gone .

typescript How to constrain Promise The type of ?

Promise Generic functions


interface Promise<T> {
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
 Copy code 
interface foo {
bar: ()=>Promise<string>,
baz: ()=>Promise<number[]>,
car: (id)=>Promise<boolean[]>
}
 Copy code 

typescript Medium keyof How to use ?

Simplest

type Point = { x: number; y: number };
type P = keyof Point; // 'x' | 'y'
let foo: P = 'x';
let bar: P = 'y';
let baz: P = 'z'; // 
 Copy code 

Commonly used

interface Person {
name: string;
age: number;
location: string;
}
type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person }; // string
type P1 = Person["name"]; // string
type P2 = Person["name" | "age"]; // string | number
type P3 = string["charAt"]; // (pos: number) => string
type P4 = string[]["push"]; // (...items: string[]) => number
type P5 = string[][0]; // string
 Copy code 

keyof Make function type safe (type-safe)

function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]; // Inferred type is T[K]
}
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]) {
obj[key] = value;
}
let x = { foo: 10, bar: "hello!" };
let foo = getProperty(x, "foo"); // number
let bar = getProperty(x, "bar"); // string
let oops = getProperty(x, "wargarbl"); // Error! "wargarbl" is not "foo" | "bar"
setProperty(x, "foo", "string"); // Error!, string expected number
 Copy code 

Partial,Required,Readonly,Pick The implementation principle of generic tool type

type Partial<T> = {
[P in keyof T]? : T[P];
}
 Copy code 
type Required<T> = {
[P in keyof T]?- : T[P];
}
 Copy code 
type Readonly<T> = {
readonly [P in keyof T] : T[P];
}
 Copy code 
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
 Copy code 

typescript Medium typeof How to use ?

js Medium typeof Mainly used in expression context , and ts Medium typeof Mainly used for type context .

let s = "hello";
let n: typeof s;
// ^ = let n: string
 Copy code 
type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>;
// ^ = type K = boolean
 Copy code 
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;
// ^ = type P = {
// x: number;
// y: number;
// }
 Copy code 

typescript Medium non-null assert operator What is it? ?

Not null Assertion operators : When it comes to null when , An assertion occurs , Throw an exception . Optional chain : When it comes to null/undefined when , return undefined.

Non null assertion operator and optional chain operator test

// Non-Null Assertion Operator
const obj = null;
interface Entity {
name?: string;
}
// Non empty assertion operators 
function nonNull(e?: Entity) {
const s = e!.name; // An assertion occurs , Throw out TypeError
}
try {
nonNull(obj);
} catch (e) {
console.error("nonNull catch", e); // TypeError: Cannot read property 'name' of null
}
// Optional chain 
function optionalChaining(e?: Entity) {
const s = e?.name;
console.log(s); // undefined
}
optionalChaining(obj);
 Copy code 

Used for null detection of function return value

function returnNullFunc() {
return null;
}
try {
returnNullFunc()!.age;
} catch (e) {
console.error("returnNullFunc", e); // TypeError: Cannot read property 'age' of null
}
function returnNonNullFunc() {
return {
age: "18"
};
}
returnNonNullFunc()!.age;
 Copy code 

On-line demo:codesandbox.io/s/non-null-…

Looking forward to communicating with you , Common progress :

Strive to be an excellent front end engineer !

版权声明
本文为[While you're young 233]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503112204011n.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless