调用函数时,函数名和参数之间的“类型断言”是什么?

Gre*_*ade 0 assertion typescript

在这个Typescript React 入门指南中,它给出了:

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',   
});
Run Code Online (Sandbox Code Playgroud)

这个断言在那里做什么?

我找不到定义此语法的位置,也无法“推断”它的含义。

Fen*_*ton 6

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

类型断言

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

const x = <HTMLAnchorElement>document.getElementById('myLink');
Run Code Online (Sandbox Code Playgroud)

类型断言出现在表达式之前并表示“实际上这是一个锚点,而不仅仅是一个通用元素”。

泛型

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

这个函数接受一个字符串并返回它。

function example(input: string): string {
    return input;
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以添加另一个接受一个数字并返回它的函数,但实际上我们的函数并不关心参数的类型,或者返回类型——只要它们相同......

因此,与其为每种类型重复该函数,我们可以说,“类型将是TT稍后将在何处定义”。

function example<T>(input: T): T {
    return input;
}
Run Code Online (Sandbox Code Playgroud)

显式类型参数

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

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

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

const num = example<number>(3);
Run Code Online (Sandbox Code Playgroud)

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

隐式类型参数

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

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

const str = example('str');

const num = example(3);
Run Code Online (Sandbox Code Playgroud)