ค้นหาเว็บไซต์

typescript - จับคู่ "any" แต่ไม่ใช่อาเรย์


ฉันกำลังพยายามทำให้ฟังก์ชันถูกพิมพ์เพื่อส่งค่ากลับ any แต่ไม่ใช่ array.

บางอย่างเช่นนี้:

Not<any, any[]>
interface Specific {
  name: string;
}

const makeOneCore = (): any => {
  return {};
};

const makeManyCore = (): any[] => {
  return [{}];
};

const makeOne = (): Specific => {
  return makeOneCore();
};

const makeMany = (): Specific[] => {
  return makeManyCore();
};

const makeManyShouldFail = (): Specific[] => {
  return makeOneCore();
};

ฉันต้องการพิมพ์ makeOneCore เพื่อให้ makeManyShouldFail เป็นข้อผิดพลาดของ TypeScript เพราะมันควรตรงกับ any ในฐานะที่เป็น array ที่เป็นไปได้

กำลังหาวิธีที่ hello ใช้ได้และ boom ใช้ไม่ได้

type NotArray<T> = T extends Array<any> ? never: T;

type v = NotArray<Array<any>>;

const hello: v = {};
const boom: v = [];

console.log({ hello, boom });

คำตอบ #1

ลองอะไรแบบนี้ดู

type NotArray<T> = T extends Array<any> ? never: T;

type A = NotArray<Array<any>>; // never
type B = NotArray<Array<string>>; // never
type C = NotArray<boolean>; // boolean

ประเภท never ไม่สามารถกำหนดค่าให้กับประเภทอื่นได้