guitarman
guitarman

Reputation: 175

Defining a string union type in TypeScript

I have the following code that is given a ReportType and then locates that types information such as publications.

export const reportTypeFind = (type: string): ReportType | null => (reportTypes.find(t => t.type === type) ?? null);

const reportTypes = [
    {
        type: 'Mood', 
        header: 'Mood Disorders',
        publication: 'Roseberry K',
        biomarkers: 144,
        CPT: '02'
    },
    {
        type: 'Pain',
        header: 'Pain',
        publication: 'Roseberry K',
        biomarkers: 36,
        CPT: '0U'
    }
];

and the following ReportType defined here:

export type ReportType = {
    type: string;
    header: string;
    publication: string;
    biomarkers: number;
    CPT: string;
};

I'm using the type to find publications and adding them to string within my code like this:

const reporttype = 'Mood';
const publication = ('Test - ' + reportTypeFind(reporttype)?.publication);

I was told to do the following, but I'm not sure how to go about this or what it will accomplish:

Use string interpolation:

`foo ${ expr }`
Also: if the reporttype can't be found your optional chaining expression will result in a 'null' being rendered.
Three options:

Define a string union type ReportType (and change the other type to ReportInfo (probably better anyway). That way you get failures at compile time if you use the wrong type name.

Can someone show me how this would look as described above? Thank you.

Upvotes: 0

Views: 123

Answers (1)

Mike
Mike

Reputation: 1375

You can define String union type in typescript as

type stringUnionType = 'typeA' | 'typeB' | 'typeC'

i rewrited your code in Playground

But the problem is that your data in reportTypes does not seams to be constant. If so, it can not be used for type check in compile time. and you need to rebuild publication construction paying attention to the case when reportType is not found

const reporttype = 'Mood';
const report = reportTypeFind(reporttype); 
if(report){
   const publication = ('Test - ' + report);
}
else {
    //!!!
}

But in the case of constant ReportTypes you code can be reduced to something like that

type constReportTypesNames = 'Mood' | 'Pain';
const constReportTypes: Record<constReportTypesNames, ReportType> = {
    'Mood': {
        type: 'Mood', 
        header: 'Mood Disorders',
        publication: 'Roseberry K',
        biomarkers: 144,
        CPT: '02'
    },
    'Pain': {
        type: 'Mood', 
        header: 'Mood Disorders',
        publication: 'Roseberry K',
        biomarkers: 144,
        CPT: '02'
    },
} as const;
type constRepostTypeNames = keyof typeof constReportTypes;
function reportTypeFind2(t: constRepostTypeNames){
    return constReportTypes[t];
}

reportTypeFind2('xxx'); //compile time error
reportTypeFind2('Pain');

Upvotes: 1

Related Questions