调用函数时,函数名和参数之间的 'type assertion' 是什么意思?

What is a 'type assertion' between the function name and parameters, on calling a function?

在此Typescript React starter guide中给出:

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',   
});

这个断言在那里做什么?

我找不到此语法的定义位置,也无法"deduce"了解它的含义。

这不是类型断言,它是类型参数,用于泛型类型。

类型断言

首先,这是一个类型断言...

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

类型断言出现在表达式之前并表示 "actually this is an anchor, not just a general element"。

泛型

现在让我们看看泛型...

此函数接受一个字符串并return对其进行处理。

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

现在我们可以添加另一个函数,它接受一个数字并 returns 它,但实际上我们的函数并不关心参数的类型,或者 return 类型 - 只要因为它们是一样的...

因此,我们可以说,"the type will be T, where T will be defined later on"。

,而不是为每种类型重复函数
function example<T>(input: T): T {
    return input;
}

显式类型参数

当您使用泛型(可以是 class、函数或方法)时,您可以显式提供类型参数,如下所示:

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

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

const num = example<number>(3);

它们看起来有点像类型断言,但它们出现在不同的位置。

隐式类型参数

在许多情况下,您不需要显式传递类型参数,因为编译器可以为您解决。

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

const str = example('str');

const num = example(3);