A.S.: The question is not about "Why is there an error?", but rather about "Why does the error go away if I barely change it?".
我有一个相对简单的逻辑来为正则表达式验证器函数创建参数,该函数从source
和flags
个字符串输入的组合中收集正则表达式,或者直接从正则表达式输入中收集正则表达式;在这两种情况下,它都需要验证配置.有些输入是可选的,有些是必需的.
它看起来是这样的:
type Options = { foo: 'bar' }
type ArgsRegExp = [first: RegExp, second?: Options]
type ArgsString = [first: string, second?: string, third?: Options]
type Args = ArgsRegExp | ArgsString
interface Params {
readonly pattern: RegExp
readonly options?: Options
}
function getParams(args: ArgsRegExp): Params
function getParams(args: ArgsString): Params
function getParams([first, second, third]: Args): Params {
if (first instanceof RegExp) {
return {
pattern: first,
options: second,
// ^^^^^^ Error!
}
}
return {
pattern: new RegExp( // weird new lines are explained in the playground
first,
second
// ^^^^^^ Error!
),
options: third,
}
}
100.
这里有一个错误:second
arg总是string | Options | undefined
,因此在两种情况下都不能赋值(在第一种情况下必须是Options | undefined
,在第二种情况下必须是string | undefined
).
This error is expected,而且(如果我理解正确的话)与https://github.com/microsoft/TypeScript/issues/30581有关
然而,not所期望的是,一段非常相似的代码(这里有the diff view段)可以很好地工作,而不会产生任何可分配性问题,因为它完美地缩小了您希望的项目:
type Common = 'c'
type ArgsRegExp = [first: 'a0', second?: Common]
type ArgsString = [first: 'b0', second?: 'b1', third?: Common]
type Args = ArgsRegExp | ArgsString
interface Params {
readonly custom: string
readonly common?: Common
}
function getParams(args: ArgsRegExp): Params
function getParams(args: ArgsString): Params
function getParams([first, second, third]: Args): Params {
if (first === 'a0') {
return {
custom: first,
common: second,
// ~~~~~~ No error?
}
}
return {
custom: // weird new lines are explained in the playground
first +
second,
// ~~~~~~ No error?
common: third,
}
}
100.
这是怎么回事?Why does this work, but the original example doesn't?我知道类型不同,但我不能准确指出是哪种差异导致了两个例子的行为不同.