我们只是没有一种很好的方法来表示它,既可以捕捉所有的边缘情况,又可以明智地添加到内置的类型中.虽然你可以用这样的东西来让它工作,
interface Array<T> {
map<V>(predicate: (value: T, index: number, array: Array<T>) => V): { [K in keyof this]: V };
}
它在某些情况下可能会失败(我已经在unknown[]
中发现了一个映射never[]
的结果),虽然我们可以修补这些单独的情况(使用更多重载或条件类型),但使用或维护根本不可行.
这个does可以工作,但我不建议增加这样的内置功能……
const foo: [string, ...string[]] = ['narf'];
const bar: [string, ...string[]] = foo.map((x) => x); // okay
相反,我只会使用断言,这样其他查看代码的文字脚本开发人员就不会奇怪,"等一下,为什么这会起作用?"
const foo: [string, ...string[]] = ['narf'];
const bar: [string, ...string[]] = foo.map((x) => x) as [string, ...string[]]; // okay
当然,您可以自由地使用您喜欢的任何方式.
相关:microsoft/TypeScript#29841
Playground个
再进行一次理智判断,这在使用上述增强功能时也是有效的.
const baz: [number, ...number[]] = foo.map((x) => x.length);