我正在尝试将可选链接与数组而不是对象一起使用,但不确定如何执行此操作:
这就是我想要做的myArray.filter(x => x.testKey === myTestKey)?[0]。还用一个函数尝试类似的事情:
let x = {a: () => {}, b: null}
console.log(x?b());
Run Code Online (Sandbox Code Playgroud)
但是它给出了这样的错误,所以如何将它与数组或函数一起使用。
TypeScript 3.7 现在支持可选的链操作符。因此,您可以编写如下代码:
const value = a?.b?.c;
Run Code Online (Sandbox Code Playgroud)
即,您可以使用此运算符访问对象的属性,其中对象本身可能是null或undefined。现在我想做的基本相同,但属性名称是动态的:
const value = a?[b]?.c;
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个语法错误:
错误 TS1005: ':' 预期。
我在这里做错了什么?这甚至可能吗?
PS:提案似乎暗示这是不可能的(但也许我的语法示例错了)。
我有一个带有一些可选字段和该类型变量的 TypeScript 接口:
interface Foo {
config?: {
longFieldName?: string;
}
}
declare let f: Foo;
Run Code Online (Sandbox Code Playgroud)
我想放入longFieldName一个同名的变量。
如果config不是可选的,我会使用解构赋值来做到这一点而不重复longFieldName. 但确实如此,所以我收到了一个类型错误:
const { longFieldName } = f.config;
// ~~~~~~~~~~~~~ Property 'longFieldName' does not exist on type '{ longFieldName?: string | undefined; } | undefined'.
Run Code Online (Sandbox Code Playgroud)
我可以使用可选链接来简洁地处理这种undefined情况:
const longFieldName = f?.config.longFieldName; // OK, type is string | undefined
Run Code Online (Sandbox Code Playgroud)
但现在我要重复一遍longFieldName。
我可以吃蛋糕也吃吗?我可以使用可选链来处理这种undefined情况而不重复longFieldName吗?如果没有,最简洁/惯用的解决方法是什么?请参阅游乐场链接。
在我的项目中,我使用 TS 3.7.2,它应该支持可选链接。但是当我尝试这样使用它时:const state = urlParams.state?.toString()我收到错误:
当前未启用对实验性语法“optionalChaining”的支持
将 @babel/plugin-proposal-optional-chaining ( https://git.io/vb4Sk ) 添加到 Babel 配置的“插件”部分以启用转换。
我查看了发行说明,没有看到有关为该功能添加 tsconfig 选项的任何要求。
我想知道我已经在使用 TS 时是否需要 babel 插件和配置,我应该如何修复错误?
设想:
这样做的好处是包更小,开发时的周转时间要快得多。
现在我们想开始使用第4 阶段的 可选链接功能,该功能可以在 Chrome 中使用标志启用。
我试着用谷歌搜索这个,我能找到的只是babel 有一个插件。
问题:有什么方法可以让 webpack 在省略 babel 的同时接受这种语法?
以下是 webpack 当前报告的内容:
ERROR in ./src/js/components/custom-select.js 245:12
Module parse failed: Unexpected token (245:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| */
| focus() { …Run Code Online (Sandbox Code Playgroud) 注意:代码使用的是spread syntax,而不是rest parameters。
const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}
console.log(fn1?.(...args, fn2, fn3))
Run Code Online (Sandbox Code Playgroud)
错误:
console.log(fn1?.(...args, fn2, fn3))
^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function
Run Code Online (Sandbox Code Playgroud) 我想不通的是如何让 TS 正确编译它。我的项目中没有出现任何语法错误,但是:
let imageFileId = (await db.query(sql`select id from image_files where sha256=${sha256}`))[0]?.id;
Run Code Online (Sandbox Code Playgroud)
正在输出为:
let imageFileId = (await db.query(mysql3_1.sql `select id from image_files where sha256=${sha256}`))[0]?.id;
Run Code Online (Sandbox Code Playgroud)
在我们获得 Node.js 的原生支持之前,它不会运行。
这是我的 tsconfig:
{
"compilerOptions": {
"strict": true,
"importHelpers": false,
"inlineSources": true,
"noEmitOnError": true,
"pretty": true,
"module": "commonjs",
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": false,
"removeComments": false,
"preserveConstEnums": false,
"sourceMap": true,
"lib": ["es2018"],
"skipLibCheck": false,
"outDir": "dist",
"target": "esnext",
"declaration": false,
"resolveJsonModule": true,
"esModuleInterop": false,
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"paths": …Run Code Online (Sandbox Code Playgroud) 我正在尝试通过TS 中可用的可选链接提供的安全性访问动态属性。然而,这似乎是无效的。
export const theme = {
headers: {
h1: {
},
h6: {
color: '#828286'
},
},
}
console.info(theme?.headers?.['h6']?.color ?? '#000') //will pass
console.info(theme?.headers?.['h1']?.color ?? '#000') //will fail
Run Code Online (Sandbox Code Playgroud)
Identifier expected. TS1003
10 | const StyledTypography = styled.div`
11 | margin: 0;
> 12 | color: #000; ${({theme}) => theme?.headers?.[variant]?.color ?? '#000'}
| ^
13 | `
14 | return (
15 | <StyledTypography as={variant}>
Run Code Online (Sandbox Code Playgroud)
似乎可选更改将应用于[]作为类型的可选,但不适用于内部的值。
我怎样才能使这个成为可选而不必做[undefined || someDefaultValue]?
据我所知,空安全运算符不适用于数组。是否有另一种方法可以通过数组链接达到相同的效果?
例如:
$array = [];
if (isset($array['a'])) {
if (isset($array['a']['b'])) {
// run
}
}
Run Code Online (Sandbox Code Playgroud)
变成:
$array<null-safe-oprator>['a']<null-safe-operator>['b'];
Run Code Online (Sandbox Code Playgroud)
谷歌搜索没有透露任何有关该主题的信息。
来自 C# 背景的空条件运算符允许您调用函数以避免可能的空引用异常,如下所示:
Func<int> someFunc = null;
int? someInteger = someFunc?.Invoke();
// someInteger == null
Run Code Online (Sandbox Code Playgroud)
鉴于 Typescript 具有具有非常相似功能的“可选链接运算符”,.?我想知道是否有一种方法可以使用类似简洁的代码来完成相同的操作。我能想到的最好的方法是使用条件表达式:
let someFunc: (() => number) | undefined = undefined;
let someNumber = someFunc !== undefined ? someFunc() : undefined;
Run Code Online (Sandbox Code Playgroud)
typescript ×7
javascript ×6
arrays ×2
function ×1
node.js ×1
php ×1
tsconfig ×1
v8 ×1
webpack ×1