2

In this Typescript React starter guide it gives:

import { createStore } from 'redux';

interface StoreState {
    languageName: string;
    enthusiasmLevel: number;
}

function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {
    // returns a StoreState
}
const store = createStore<StoreState>(enthusiasm, {
     enthusiasmLevel: 1,
     languageName: 'TypeScript',   
});

What is this assertion doing there?

I couldn't find where this syntax is defined, and can't "deduce" what it means.

2
  • 1
    Have a look at generics Commented Nov 14, 2017 at 11:59
  • Thanks - I'd pay that as an answer: sometimes simple is correct and good :) Commented Nov 14, 2017 at 12:00

1 Answer 1

11

This isn't a type assertion, it is a type argument, which is used for generic types.

Type Assertions

Firstly, here's a type assertion...

const x = <HTMLAnchorElement>document.getElementById('myLink');

The type assertion appears before the expression and says "actually this is an anchor, not just a general element".

Generics

Now let's look at generics...

This function takes a string and returns it.

function example(input: string): string {
    return input;
}

Now we can add another function that takes a number and returns it, but actually our function doesn't care about the type of the parameter, or the return type - as long as they are the same...

So instead of repeating the function for each type, we can say, "the type will be T, where T will be defined later on".

function example<T>(input: T): T {
    return input;
}

Explicit Type Argument

When you use something generic (it can be a class, or a function, or a method), you can supply the type argument explicitly, like this:

function example<T>(input: T): T {
    return input;
}

const str = example<string>('str');

const num = example<number>(3);

They look a bit like type assertions, but they appear in a different location.

Implicit Type Argument

In many cases, you don't need to explicitly pass the type argument, as the compiler can work it out for you.

function example<T>(input: T): T {
    return input;
}

const str = example('str');

const num = example(3);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.