简体   繁体   中英

Name Union Types in Typescript

I am working on a project that uses Union types extensively and consistently throughout the project. I'd like to name a particular union type, so that I don't have to keep explicitly defining the union throughout my code (introducing the probability of getting it wrong somewhere).

For example, rather than:

function doSomething(parm: FirstType | SecondType){...}
function doSomethingElse(parm: FirstType | SecondType){...}

I'd like to have something like:

class compositeType = FirstType | SecondType;
function doSomething(parm: compositeType) {...}
function doSomethingElse(parm: compositeType) {...}

This would help adhere to the DRY principle, and reduce errors in my codebase. Is this possible in Typescript? Note: I do not control FirstType and SecondType, as they are returned from third party libraries, so using inheritance is not an option here, AFAIK.

查看类型别名

type FirstOrSecond = FirstType | SecondType;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM