Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

Use of never keyword in typescript

TS documentation says, "the never type represents the type of values that never occur. Variables also acquire the type never when narrowed by any type guards that can never be true."

I didn't understand its usage, can anybody give me an answer with some examples.

question from:https://stackoverflow.com/questions/42291811/use-of-never-keyword-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. "the never type represents the type of values that never occur."

It might be return type of function that never returns:

const reportError = function () {
    throw Error('my error');
}

const loop = function () {
    while(true) {}
}

Here, both reportError and loop type is () => never.

  1. "Variables also acquire the type never when narrowed by any type guards that can never be true"

With operators like typeof, instanceof or in we can narrow variable type. We may narrow down the type the way, that we are sure that this variable in some places never occurs.

function format(value: string | number) {
    if (typeof value === 'string') {
        return value.trim();
    } else {
        return value.toFixed(2); // we're sure it's number
    }

    // not a string or number
    // "value" can't occur here, so it's type "never"
}
  1. Common use case

Except better type safety (as in cases described above), never type has another use case - conditional types. With never type we can exclude some undesired types:

type NonNullable<T> = T extends null | undefined ? never : T;

type A = NonNullable<boolean>;            // boolean
type B = NonNullable<number | null>;      // number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...