programing

유형 스크립트를 사용하여 Vue 데이터 개체에서 데이터 유형 설정

copyandpastes 2022. 7. 30. 21:04
반응형

유형 스크립트를 사용하여 Vue 데이터 개체에서 데이터 유형 설정

현재 웹 팩 프로젝트에서 Vue.js with Typescript를 사용하고 있습니다.

의 「권장 설정」에 기재되어 있는 바와 같이tsconfig.json다음과 같은 것이 있습니다.

"strict": true,

내 컴포넌트 중 하나에 다음과 같은 것이 있습니다.

declare interface Player {
    cod: string,
    param: string
  }

export default Vue.extend({
    name: 'basecomponent',
    data() {
      return {
        players: []
      };
    },
    created() 
      let self = this
      axios.get('fetch-data')
        .then((response) => {
          let res: Players[] = response.data;
          for(let i = 0; i < res.length; i++){
              self.players.push(res[i]);
          }
        })
        .catch((error: string) => {
          console.log(error);
       });
    },
 });

컴파일을 시도하면 다음과 같이 됩니다.

 error TS2345: Argument of type 'Player' is not assignable to parameter of type 'never'.

왜냐하면 나는 믿기 때문이다players: []가지다never[]유형.

질문입니다. Vue 데이터 객체 속성을 어떻게 유추할 수 있습니까?

Jooshua의 답변에 덧붙이자면 데이터가 커질수록 코드가 너무 상세해지지 않도록 플레이어의 유형을 인라인으로 선언할 수 있습니다.

data() {
  return {
    players: [] as Player[]
  };
},

다른 옵션:

data() {
  return {
    players: new Array<Player>()
  };
},

이 조작은 유효합니다.

declare interface Player {
  cod: string,
  param: string
}

declare interface BaseComponentData {
  players: Player[]
}

export default Vue.extend({
  name: 'basecomponent',
  data(): BaseComponentData {
    return {
      players: []
    };
  },
})

당신의.datamethod에 선언되지 않은 반환값이 있습니다.

1개를 지정하면 TypeScript는 무엇을 기대할 수 있는지 알 수 있습니다.players.

확장만 하면 됩니다.data() {선.

예:

data() {
  return {
    players: []
  };
},

다음과 같이 해야 합니다.

data() : {
  players: Array<any>, // if possible, replace `any` with something more specific
} {
  return {
    players: []
  };
},

짠!players현재 유형입니다.Arrayany.

코드를 짧게 유지하면서 일반적인 구문에 더 가까운 다른 방법을 찾았습니다.

data() {
  return new class {
    players: Player[] = []
  }();
},

'<>' 구문을 사용하는 형식 어설션은 금지됩니다.대신 'as' 구문을 사용하십시오.

다음과 같이 표시됩니다.

players: [] as Player[]

미래에 누군가 이것을 발견하게 될 경우를 대비해서, 여기 제 문제를 해결한 답이 있습니다.좀 더 "단어적"이지만, 이것은 적절한 유형 추론을 합니다.Vue.extend()컴포넌트 정의:

interface Player {
  cod: string,
  param: string
}

// Any properties that are set in the `data()` return object should go here.
interface Data {
  players: Player[];
}

// Any methods that are set in the "methods()" should go here.
interface Methods {}

// Any properties that are set in the "computed()" should go here.
interface Computed {}

// Any component props should go here.
interface Props {}

export default Vue.extend<Data, Methods, Computed, Props>({
    name: 'basecomponent',
    data() {
      return {
        players: []
      };
    },
    // You probably will want to change this to the "mounted()" component lifecycle, as there are weird things that happen when you change the data within a "created()" lifecycle.
    created() {
      // This is not necessary.
      // let self = this
      // If you type the Axios.get() method like this, then the .data property is automatically typed.
      axios.get<Players[]>('fetch-data')
        .then(({ data }) => {
          // This is not necessary.
          // let res: Players[] = response.data;
          // for(let i = 0; i < data.length; i++){
          //     self.players.push(data[i]);
          // }
          this.players = data;
        })
        .catch((error: string) => {
          console.log(error);
       });
    },
 });

언급URL : https://stackoverflow.com/questions/47810218/set-data-type-in-vue-data-object-with-typescript

반응형