Mick
Mick

Reputation: 917

String validation in Typescript

Coming from Javascript I need some advice on how to do string validation in Typescript.

Usually in Javascript you can just check the string as if it was a boolean, but with strong types, you get a compiler error.

A couple of solutions I thought of, but don't really like is you could do !!myString or change the return type. Is checking for null, undefined and empty string the way to do it?

See example:

function stringIsValid(myString: String) : Boolean {
    return myString; // compiler error
}

var isValid = stringIsValid(null);

Playground

Upvotes: 1

Views: 10617

Answers (2)

Milkncookiez
Milkncookiez

Reputation: 7377

The types from TS will not help you do runtime type validation on your variables, because TS only works at compile-time. There is a handy typeof command in JS to do type validation:

typeof myString === 'string'

The function you wrote

function stringIsValid(myString: string) : boolean {
    return myString;
}

will give you TS error at transpilation (compile-time), but these types will have no effect when you actually run your program. Here's an example of how to write it with proper typing and proper runtime check:

function stringIsValid(myString: string) : boolean {
    return typeof myString === 'string';
}

Upvotes: 3

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

You probably want to just use one of these, functionally they're the same:

function stringIsValid(myString: String): Boolean {
    return Boolean(myString);
}

or

function stringIsValid(myString: String): Boolean {
    return !!myString;
}

Upvotes: 3

Related Questions