这是我的职责:
function foo(
hello: fooOptions = {}
): [Record<string, unknown> | null, Record<string, unknown> | null] {是否有可能重构这一行,以使它看起来稍微好一点?
[Record<string, unknown> | null, Record<string, unknown> | null]发布于 2021-01-26 10:53:52
是的,有可能:
type fooOptions = {}
type Nullable<T> = T | null
type Obj = Record<string, unknown>;
function foo(
hello: fooOptions = {}
): [Nullable<Obj>, Nullable<Obj>] {
return null as any
}更通用的解决方案:
type fooOptions = {}
type Nullable<T> = T | null
type Obj = Record<string, unknown>;
interface FixedLengthArray<T extends any, L extends number> extends ReadonlyArray<T> {
0: T;
length: L;
}
function foo1(
hello: fooOptions = {}
): FixedLengthArray<Nullable<Obj>, 2> {
return [{}, {}, {}] // expected error
}
function foo2(
hello: fooOptions = {}
): FixedLengthArray<Nullable<Obj>, 2> {
return [{}] // expected error
}
function foo3(
hello: fooOptions = {}
): FixedLengthArray<Nullable<Obj>, 2> {
return [{},{}] // ok
}
function foo4(
hello: fooOptions = {}
): FixedLengthArray<Nullable<Obj>, 3> {
return [{},{}] // expected error
}Shamelesly从这里失窃
你也可以对固定长度的数组使用递归,但有时递归可以加热你的笔记本电脑))
发布于 2021-01-26 20:47:41
另一种选择是分别创建一个类型,以便:
type ReturnResponse = [Record<string, unknown> | null, Record<string, unknown> | null];
function foo(
hello: fooOptions = {}
): ReturnResponse {我们还可以将类型放在某个单独的文件中并导出它。在一个单独的文件中,它将是:
export type ReturnResponse = [Record<string, unknown> | null, Record<string, unknown> | null];我们会在使用ReturnResponse的文件中导入它。
https://stackoverflow.com/questions/65899919
复制相似问题