我有一个类型别名Data,它是两个数据结构的联合——一个包含非空的数组,而另一个为空:
const dataEmptyArray = { data: [] }
const dataNotEmptyArray = { data: [1, 2, 3] }
type DataEmptyArray = typeof dataEmptyArray
type DataNotEmptyArray = typeof dataNotEmptyArray
type Data = DataNotEmptyArray | DataEmptyArray // <--- union here
function foo(arg:Data) {
if (arg && arg.data && Array.isArray(arg.data)) {
return arg.data.map( (d:(never|number)) => d)
// ^^^<--------- this expression is not callable
} else {
return 'no data'
}
}
const result = foo(dataEmptyArray)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在数组上调用 Array.prototype.map() 时,出现错误提示:“此表达式不可调用”
上面的代码片段可以在这里找到
我注意到,如果我将 …
我正在使用webpack,最后我看不到这个包的机会,因为似乎Object.assign完成了这项工作,但也许这个包之间有什么东西?
谢谢
Mozilla说:
map不会改变调用它的数组(尽管回调,如果被调用,可能会这样做).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
具体来说,回调传递的第三个参数是:
调用了数组映射.
我假设这意味着内存中的数组位置通过引用复制到回调中.
因此,通过改变第三个参数,我们应该改变原始数组,但是以下两个片段会产生相互矛盾的结果:
情况1,重新分配第三个参数没有改变原始数组:
var A = [1, 2, 3];
A.map((v,i,_A) => {
console.log("_A is the array map invoked on: ", _A===A); // true
_A = []; // reassign an empty array
return v;
});
console.log("'A' did not mutate:", A) // [1, 2, 3] did not mutateRun Code Online (Sandbox Code Playgroud)
情况2,将第三个参数设置为零长度会改变原始数组:
var B = [1, 2, 3];
B.map((v,i,_B) => {
console.log("_B is the array map invoked on: ", _B===B); // true
_B.length = 0; // clearing the array by …Run Code Online (Sandbox Code Playgroud)type Func = (foo:string) => void
// function expression
const myFunctionExpression:Func = function(foo) {
console.log(foo)
}
Run Code Online (Sandbox Code Playgroud)
在上面的 Typescript 片段中,我使用类型别名来注释函数表达式中的变量。
类型别名:
type Func = (foo:string) => void
Run Code Online (Sandbox Code Playgroud)
可在另一个函数表达式中重用以减少重复。
我的问题是:有没有办法重用这个类型别名来注释函数声明?
// function declaration
function myFunctionDeclaration(foo:string):void {
console.log(foo)
}
Run Code Online (Sandbox Code Playgroud)
在网上搜索后,我似乎找不到这样的语法,我错过了什么?
谢谢
更新:
在撰写本文时,github 上有一张请求此功能的票证:建议:函数声明的类型注释和接口 #22063(感谢来自 @jcalz 的评论)
我正在用 webpack4 测试 react-router4,但我无法获得 webpack-dev-server 的设置:
{historyApiFallback: true}
Run Code Online (Sandbox Code Playgroud)
上班。这个用法在 webpack3 中工作得很好,所以我不确定是什么问题......这是我的 webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = () => {
return {
mode: 'development',
devtool: 'source-map',
devServer: {
port: 8888,
historyApiFallback: true,
stats: 'minimal'
},
resolve: {
extensions: ['*', '.mjs', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.m?jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
title:'React Lab',
template: 'src/index.html'
})
]
}
}
Run Code Online (Sandbox Code Playgroud)
这是我使用 react-router4 的简单反应应用程序:
import React from 'react'; …Run Code Online (Sandbox Code Playgroud)