官术网_书友最值得收藏!

Simplifying type declarations with type aliases

Something that goes hand in hand with intersection types and union types are type aliases. Rather than cluttering our code with references to string | number | null, TypeScript gives us the ability to create a handy alias that is expanded out by the compiler into the relevant code.

Suppose that we want to create a type alias that represents the union type of string | number, then we can create an alias that looks as follows:

type StringOrNumber = string | number;

If we revisit our range validation sample, we can change the signature of our function to use this alias, as follows:

class UnionRangeValidationWithTypeAlias extends RangeValidationBase {
IsInRange(value : StringOrNumber) : boolean {
if (typeof value === "number") {
return this.RangeCheck(value);
}
return this.RangeCheck(this.GetNumber(value));
}
}

The important thing to notice in this code is that we don't really create any new types here. The type alias is just a syntactic trick that we can use to make our code more readable and, more importantly, help us to create code that is more consistent when we are working in larger teams.

We can combine type aliases with types to create more complex type aliases as well. If we wanted to add null support to the previous type alias, we could add this type:

type NullableStringOrNumber = StringOrNumber | null;

As the compiler still sees the underlying type and uses that, we can use the following syntax to call our IsInRange method:

let total : string | number = 10;
if (new UnionRangeValidationWithTypeAlias(0,100).IsInRange(total)) {
console.log(`This value is in range`);
}

Obviously, this doesn't give us very consistent-looking code, so we can change string | number to StringOrNumber.

主站蜘蛛池模板: 盐源县| 福鼎市| 乌拉特中旗| 玉山县| 莫力| 建瓯市| 泾阳县| 伊金霍洛旗| 乌苏市| 芜湖县| 织金县| 桦南县| 蕲春县| 韩城市| 太白县| 上杭县| 武宁县| 建德市| 应城市| 合川市| 思南县| 吴川市| 巴中市| 崇仁县| 河北区| 香港| 东山县| 满城县| 游戏| 天峻县| 思茅市| 苍南县| 武川县| 克山县| 刚察县| 永善县| 顺昌县| 台湾省| 如东县| 永仁县| 宿州市|