我需要將嵌套物件作為方法引數傳遞。行內一切正常,但傳遞變數將導致 TS 錯誤,因為例如{ a: 'x' }將變為{ a: string }。解決方案是as const在該變數上使用。但這不適用于具有陣列等的物件。我被迫在該物件內部多次使用“as const”,而不是最后只使用“as const”。為什么?
type A = 'xxx' | 'yyy' | 'zzz'
type Demo = {
a: A,
b: number,
}[]
const demoMethod = (demo: Demo) => {
console.log(demo)
}
/* Example #1 - OK */
demoMethod([
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
])
/* Example #2 - ERROR */
const demo2 = [
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
]
demoMethod(demo2)
/* Example #3 - OK */
const demo3 = [
{ a: 'xxx', b: 111 } as const,
{ a: 'yyy', b: 222 } as const,
{ a: 'xxx', b: 333 } as const,
]
demoMethod(demo3)
/* Example #4 - ERROR */
const demo4 = [
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
] as const
demoMethod(demo4)
TS游樂場
即使示例#1 和#2 100% 相同,對我來說也沒有任何意義,#2 不起作用,我被迫使用多個'as const' 更改我的資料,而不是按原樣傳遞它。有沒有更好的解決方案來強制 TS 以與行內引數相同的方式處理我的 const 引數?
編輯:請注意,我僅在示例目的中定義了型別和方法。在現實生活中,此方法來自外部包,并且沒有匯出型別。
uj5u.com熱心網友回復:
由于您無權訪問該型別,因此您可以嘗試使用Parameters檢索它。
type a = Parameters<typeof demoMethod>[0];
// Which gives
// type a = {
// a: A;
// b: number;
//}[]
然后例如使用型別注釋!
以前的回應
而不是使用as const,你可以做const demo5: Demo = ...。
然后它將檢查您提供的值是否demo5與 type 相對應Demo。
const demo5: Demo = [
{ a: 'xxx', b: 111 },
{ a: 'abc', b: 222 }, // TypeError: Type '"abc"' is not assignable to type 'A'.
]
游樂場示例
一般來說,最好避免const a = ... as Demo;,因為 Typescript 不會做任何檢查,只是假設它a是 type Demo。
const a = 'Hello world!' as number; // Won't raise an error
const a: number = 'Hello world!'; // Will raise a type error
uj5u.com熱心網友回復:
示例 #2 不起作用,因為demo推斷為{ a: string; b: number; }[]. 這顯然不能分配給Demo,即{ a: A; b: number; }[]。您必須使用@Cr4zySheep 所說的型別注釋明確告訴 TypeScript 型別,或者demo使用:Demoas
// type annotation
const demo2: Demo = [
{ a: 'xxx', b: 111 },
{ a: 'yyy', b: 222 },
{ a: 'xxx', b: 333 },
] as Demo; // or use 'as'
demoMethod(demo2);
下面修復示例#4
只讀陣列不能分配給常規陣列。
這是因為常規陣列是可變的。如果您為需要可變陣列的東西提供不可變陣列,那顯然是型別不匹配。但是,可以將常規陣列分配給不可變陣列,因為不需要對常規陣列進行變異。
type Demo = ReadonlyArray<{
a: A,
b: number,
}>;
因此,這將是建議的解決方案;只需使用只讀陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436892.html
標籤:javascript 打字稿
