programing

spread 구문 및 typescript에 새로운 Set() 사용

javajsp 2023. 2. 28. 23:15

spread 구문 및 typescript에 새로운 Set() 사용

고유 번호를 얻기 위해 다음 코드를 사용하고 있습니다.

let uniques = [ ...new Set([1, 2, 3, 1, 1]) ]; // [1, 2, 3]

단, 타이프스크립트리포트는 다음 에러입니다.'Set' 유형이 어레이 유형이 아닙니다.저는 타이프 닌자가 아닙니다만, 어떤 문제가 있는지 가르쳐 주실 수 있겠습니까?

업데이트: Typescript 2.3에서 추가 가능"downlevelIteration": true이것은 ES5를 타겟으로 하고 있을 때 동작합니다.

의 단점downlevelIterationTS는 트랜스프레스를 할 때 꽤 많은 보일러 플레이트를 주입해야 합니다.질문의 한 줄은 추가된 보일러 플레이트 21줄로 바뀝니다. (Typescript 2.6.1의 경우)

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
var uniques = __spread(new Set([1, 2, 3, 1, 1]));
console.log(uniques);

이 보일러 플레이트는 다운레벨 반복을 사용하는 파일마다 1회 주입됩니다.이 보일러 플레이트는,"importHelpers"옵션을 선택합니다.(다운 레벨의 반복에 대해서는, 이 블로그의 투고를 참조해 주세요.importHelpers)

또는 ES5 지원이 중요하지 않은 경우 처음부터 "es6"를 대상으로 할 수도 있습니다.이 경우 원래 코드는 "downlevelIteration" 플래그가 없어도 작동합니다.


원답:

이것은 타자기 ES6 전치 기호의 일종으로 보인다....오퍼레이터는 반복기 속성이 있는 모든 항목에 대해 작업해야 합니다(접근자:obj[Symbol.iterator]세트에는 이 속성이 있습니다.

이 문제를 해결하려면Array.from먼저 집합을 배열로 변환하려면:...Array.from(new Set([1, 2, 3, 1, 1])).

Array.from 메서드를 사용하여 Set을 Array로 변환할 수도 있습니다.

let uniques = Array.from(new Set([1, 2, 3, 1, 1])) ;
console.log(uniques);

이것은 누락된 기능입니다.현재 TypeScript는 어레이 상의 반복 가능한 파일만 지원합니다.

Javascript의 경우:

[ ...new Set([1, 2, 3, 1, 1]) ]

타이프 스크립트:

Array.from(new Set([1, 2, 3, 1, 1]))

반응 상태(setState):

setCart(Array.from(new Set([...cart, {title: 'Sample', price: 20}])));

설정해야 합니다."target": "es6",tsconfig로 이동합니다.

이제 사용할 수 있습니다.SetTypscript 설정(타깃할 필요 없음)es6):

네 안에tsconfig.json, 다음 행을 추가합니다.

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    
    "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    
  },
  ...
}

tsconfig.json의 compilerOptions에서 "target"(ES6 이상) 또는 "downlevelIteration"(downlevelIteration): tsconfig.json의 compilerOptions에서 true가 필요합니다.이것으로 문제가 해결되어 정상적으로 동작하고 있습니다.당신에게도 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/33464504/using-spread-syntax-and-new-set-with-typescript