>  기사  >  웹 프론트엔드  >  Typescript의 구조화

Typescript의 구조화

王林
王林원래의
2024-07-19 10:17:09846검색

ESestructuring in Typescript

구조 분해를 사용하면 배열의 값 또는 객체의 속성을 개별 변수로 압축 해제할 수 있습니다.

장점

  • 코드를 간결하고 읽기 쉽게 만듭니다.
  • 반복적인 구조분해 표현을 쉽게 피할 수 있습니다.

일부 사용 사례

  1. Objects, Array에서 변수의 값을 가져오려면.
let array = [1, 2, 3, 4, 5];
let [first, second, ...rest] = array;
console.log(first, second, rest);
//expected output: 1 2 [3,4,5]

let objectFoo = { foo: 'foo' };
let { foo: newVarName } = objectFoo;
console.log(newVarName);
//expected output: foo

// Nested extraction
let objectFooBar = { foo: { bar: 'bar' } };
let { foo: { bar } } = objectFooBar;
console.log(bar);
//expected output: bar
  1. 객체에서 원하는 속성만 변경합니다.
  let array = [
    { a: 1, b: 2, c: 3 },
    { a: 4, b: 5, c: 6 },
    { a: 7, b: 8, c: 9 },
  ];
  let newArray = array.map(({ a, ...rest }, index) => ({
    a: index + 10,
    ...rest,
  }));
  console.log(newArray);
/* expected output: [
  {
    "a": 10,
    "b": 2,
    "c": 3    
  },
  {
    "a": 11,
    "b": 5,
    "c": 6
  },
  {
    "a": 12,
    "b": 8,
    "c": 9
  }
]*/
  1. 매개변수의 값을 독립형 변수로 추출합니다.
// Object destructuring:
  const objectDestructure = ({ property }: { property: string }) => {
    console.log(property);
  };
  objectDestructure({ property: 'foo' });
  //expected output: foo

  // Array destructuring:
  const arrayDestructure = ([item1, item2]: [string, string]) => {
    console.log(item1 , item2);
  };
  arrayDestructure(['bar', 'baz']);
  //expected output: bar baz


// Assigning default values to destructured properties:
  const defaultValDestructure = ({
    foo = 'defaultFooVal',
    bar,
  }: {
    foo?: string;
    bar: string;
  }) => {
    console.log(foo, bar);
  };
  defaultValDestructure({ bar: 'bar' });
//expected output: defaultFooVal bar
  1. 객체에서 동적 키 값을 가져옵니다.
const obj = { a: 1, b: 2, c: 3 };
const key = 'c';
let { [key]: val } = obj;
console.log(val);
//expected output: 3
  1. 값을 교환합니다.
const b = [1, 2, 3, 4];
[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
console.log(b);
//expected output : [3,2,1,4]
  1. 객체의 하위 집합을 가져옵니다.
const obj = { a: 5, b: 6, c: 7 };
const subset = (({ a, c }) => ({ a, c }))(obj);
console.log(subset); 
// expected output : { a: 5, c: 7 }
  1. 배열을 객체로 변환합니다.
const arr = ["2024", "17", "07"],
      date = (([year, day, month]) => ({year, month, day}))(arr);
console.log(date);
/* expected output: {
  "year": "2024",
  "month": "07",
  "day": "17"
} */
  1. 함수에서 기본값을 설정합니다.
function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){
    console.log(settings.i);
    console.log(settings.i2);
}
someName('hello', {i: '#123'});
someName('hello', {i2: '#123'});
/* expected output: 
#123
#fff
#1d252c
#123 
*/
  1. 배열의 길이, 함수 이름, 인수 수 등과 같은 속성을 가져오려면
let arr = [1,2,3,4,5];
let {length} = arr;
console.log(length);
let func = function dummyFunc(a,b,c) {
  return 'A B and C';
}
let {name, length:funcLen} = func;
console.log(name, funcLen);
/* expected output : 
5
dummyFunc 3
*/
  1. 배열이나 객체를 결합합니다.
//combining two arrays
const alphabets = ['A','B','C','D','E','F'];
const numbers = ['1','2','3','4','5','6'];
const newArray = [...alphabets, ...numbers]
console.log(newArray);
//expected output: ['A','B','C','D','E','F','1','2','3','4','5','6']

//combining two objects
const personObj = { firstname: "John", lastname: "Doe"};
const addressObj = { city: "some city", state: "some state" };
const combinedObj = {...personObj, ...addressObj};
console.log(combinedObj);
/* expected output: {
    "firstname": "John",
    "lastname": "Doe",
    "city": "some city",
    "state": "some state"
} */

위 내용은 Typescript의 구조화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:최고의 React Books 4다음 기사:최고의 React Books 4