假设我有一个不同类型的数据数组:
const input = ["random", 2, {a: "foo", b: "baz"}];
Run Code Online (Sandbox Code Playgroud)
Typescript可以自动推断和提取类型,例如:
type InputTypeArray = typeof input;
Run Code Online (Sandbox Code Playgroud)
这里的打字稿知道InputTypeArray是(string | number | {a:string,b:string})[];
让我们将InputType称为数组元素的类型,即:
typeof InputType = string | number | {a: string, b: string};
Run Code Online (Sandbox Code Playgroud)
我可以从InputTypeArray派生InputType吗?换句话说,我将如何编写一个接受输入元素之一作为参数的函数?
const input = ["random", 2, {a: "foo", b: "baz"}];
const myFunction = (element: InputType) => element;
input.map(myFunction);
Run Code Online (Sandbox Code Playgroud)
我如何在这里写“ InputType”?有没有办法从输入中提取出来?
我知道我可以通过在map调用中内联myFunction来解决,因为打字稿会再次推断函数内的正确类型。但是有没有办法获得这种类型呢?
Jam*_*ren 16
您可以使用此格式获取成员类型:
type InputType = typeof input[number];
Run Code Online (Sandbox Code Playgroud)
你可以阅读更多关于它(和其他一些很酷的技巧),这里的史蒂夫Holgado酒店的博客文章。
您可以通过指向数组成员来提取它,因此在使用以下代码获取数组类型时:
type A = typeof input;
Run Code Online (Sandbox Code Playgroud)
您可以使用它来获取单个项目的类型:
type B = typeof input[0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3124 次 |
| 最近记录: |