类型脚本中的可选属性类

我是新的类型脚本,我想知道什么是可选属性类在类型脚本的实用程序?这两者的区别是什么:

a?: number;


a: number | undefined;
123026 次浏览

Optional property: In Typescript you can declare a property in your interface which will be optional. Suppose you have a interface for employee and middle name is optional then your code will look like this:

interface IEmployee {
firstName: string;
lastName: string;
middleName?: string;
}

When someone will use your interface IEmployee then middleName will be optional but firstName and lastName is compulsory.

let emp: IEmployee = { firstName: "Hohn", lastName: "Doe" }

Pipe Operator: Sometimes you want that a variable can hold multiple type. If you declared a property as number then it can hold only number. Pipe operator can tell typescript that it can hold multiple type. Other case where pipe operator is very useful when you return something from function and can return multiple type depend on condition.

Hope it will help

Parameters

The difference between an optional parameter, and a parameter type number | undefined is that you don't have to supply an argument...

function a(a?: number) {
return a;
}


function b(a: number | undefined) {
return a;
}


// Okay
a();
b(1);


// Not okay: Expected 1 arguments, but got 0.
b();

This applies to functions, methods, and constructors.

Strict Null Checks

If you switch on strict null checks, you'll find that any optional parameter, or property, will get a union type automatically. That means id in the below example has the type number | undefined, even though you only specified number:

// With strict null checks, this:
class Example {
id?: number;
}


// ... is the same as this:
class Example {
id?: number | undefined;
}


// ... and this:
class Example {
id: number | undefined;
}

I would recommend using the first example as it keeps your syntax consistent between properties and parameters.