Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I check the type of a variable inside an `if` statement

There is a problem in this area

if (components[i] == **TextOptionType**) {

I’m self-debugging a plug-in for a program called obsidian.

~ObsidianDevLibrary.ts is located at Importing ~type.ts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is a problem in referring to TextOptionType as a value.

How can I solve this?

type.ts

export type TextOptionType = {
    [propName: string] : any,
    key: string,
    placeholder?: string,
    autoSave?: boolean,
    value?: boolean,
    onChange?: onChangeType,
}

ObsidianDevLibrary.ts

for (let i = 0; i < components.length; i++) {
    if (components[i] == TextOptionType) {
        componentsToReturn.push(this.addText(setting, components[i]))
    }
}

Maybe comparing TextOptionType with if is wrong grammar, but I don’t know the right way.

It may be intended to verify that the data entering the component is formatted

https://github.com/KjellConnelly/obsidian-dev-tools

>Solution :

Define a type-predicate function that checks for known members of TextOptionType, like so:

function isTextOptionType( x: unknown ): x is TextOptionType {

    const whatIf = x as TextOptionType;
    return (
        ( typeof whatIf === 'object' && whatIf !== null )
        &&
        ( typeof whatIf.key === 'string' )
        &&
        ( typeof whatIf.placeholder === 'string' || typeof whatIf.placeholder === 'undefined' )
        &&
        ( typeof whatIf.autoSave === 'boolean' || typeof whatIf.autoSave === 'undefined' )
        &&
        ( typeof whatIf.value === 'boolean' || typeof whatIf.value === 'undefined' )
        &&
        ( typeof whatIf.onChange === 'function' || typeof whatIf.onChange === 'undefined' )
    );
}

Used like so:

for( const c of components ) {
    if( isTextOptionType( c ) ) {
        componentsToReturn.push( this.addText( setting, c ) );
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading