我希望能夠從 SHAPES 陣列中選擇一個隨機元素,同時保留它const以便Shape可以在代碼的其他地方使用該型別。理想情況下,我希望能夠對陣列和非陣列使用以下randomChoice函式。constconst
const SHAPES = [
'circle',
'square',
'triangle',
] as const;
type Shape = typeof SHAPES[number];
console.log('Available shapes are:');
for (let shape of SHAPES) {
console.log(` ${shape}`);
}
function randomChoice<T>(arr: T[]): T {
let index = Math.floor(arr.length * Math.random());
return arr[index];
}
console.log('A random shape is:');
console.log(randomChoice(SHAPES));
當我運行上面的,我得到這個錯誤:
C:\ts>npx tsc test.ts
test.ts:18:26 - error TS2345: Argument of type 'readonly ["circle", "square", "triangle"]' is not assignable to parameter of type 'any[]'.
The type 'readonly ["circle", "square", "triangle"]' is 'readonly' and cannot be assigned to the mutable type 'any[]'.
18 console.log(randomChoice(SHAPES));
~~~~~~
如果我將最后一行更改為:
let choice = randomChoice(SHAPES);
console.log(choice);
我得到一個稍微不同的錯誤:
C:\ts>npx tsc test.ts
test.ts:18:27 - error TS2345: Argument of type 'readonly ["circle", "square", "triangle"]' is not assignable to parameter of type 'unknown[]'.
The type 'readonly ["circle", "square", "triangle"]' is 'readonly' and cannot be assigned to the mutable type 'unknown[]'.
18 let choice = randomChoice(SHAPES);
~~~~~~
uj5u.com熱心網友回復:
使用as constonSHAPES將其宣告為readonly陣列。as const如果可以,請洗掉,或將函式定義更改為接受Readonly<T[]>(沙箱):
function randomChoice<T>(arr: Readonly<T[]>): T {
let index = Math.floor(arr.length * Math.random());
return arr[index];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460180.html
