developer tip

Typescript d.ts 파일에 정의 된 인터페이스 속성 유형 재정의

copycodes 2020. 12. 27. 11:18
반응형

Typescript d.ts 파일에 정의 된 인터페이스 속성 유형 재정의


*.d.tsin typescript에 정의 된 인터페이스 속성의 유형을 변경하는 방법이 있습니까?

예 :의 인터페이스 x.d.ts는 다음과 같이 정의됩니다.

interface A {
  property: number;
}

내가 쓰는 typescript 파일에서 변경하고 싶습니다.

interface A {
  property: Object;
}

또는 이것은 작동합니다

interface B extends A {
  property: Object;
}

이 접근 방식이 효과가 있습니까? 내 시스템에서 시도했을 때 작동하지 않았습니다. 가능한지 확인하고 싶습니까?


기존 속성의 유형은 변경할 수 없습니다.

속성을 추가 할 수 있습니다.

interface A {
    newProperty: any;
}

그러나 기존 유형 변경 :

interface A {
    property: any;
}

오류가 발생합니다.

후속 변수 선언은 동일한 유형을 가져야합니다. 변수 'property'는 'number'유형이어야하지만 여기에는 'any'유형이 있습니다.

물론 기존 인터페이스를 확장하는 자체 인터페이스를 가질 수 있습니다. 이 경우 호환되는 유형으로 만 유형을 재정의 할 수 있습니다. 예를 들면 다음과 같습니다.

interface A {
    x: string | number;
}

interface B extends A {
    x: number;
}

그건 그렇고, 당신은 아마 Object유형으로 사용하지 말고 대신 type을 사용하십시오 any.

유형에 대한 문서에서 다음과any 같이 설명합니다.

any 유형은 기존 JavaScript와 함께 작업 할 수있는 강력한 방법으로, 컴파일하는 동안 점차적으로 유형 검사를 옵트 인 및 옵트 아웃 할 수 있습니다. Object가 다른 언어에서와 마찬가지로 비슷한 역할을 할 것으로 예상 할 수 있습니다. 그러나 Object 유형의 변수는 값을 할당 할 수만 있습니다 . 실제로 존재하는 경우에도 임의의 메서드를 호출 할 수 없습니다 .

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

먼저 필드를 필터링 한 다음 결합하는 방법을 사용합니다.

참조 유형에서 속성 제외

interface A {
    x: string
}

export type B = Omit<A, 'x'> & { x: number };

인터페이스 :

interface A {
    x: string
}

interface B extends Omit<A, 'x'> {
  x: number
}

type ModifiedType = Modify<OriginalType, {
  a: number;
  b: number;
}>

ZSkycat의 extends Omit 솔루션에서 영감을 받아 다음과 같은 결과를 얻었습니다.

type Modify<T, R> = Omit<T, keyof R> & R;

// before typescript@3.5
type Modify<T, R> = Pick<T, Exclude<keyof T, keyof R>> & R

예:

interface OriginalType {
  a: string;
  b: boolean;
  c: number;
}

type ModifiedType  = Modify<OriginalType , {
  a: number;
  b: number;
}>

// ModifiedType = { a: number; b: number; c: number; }

단계별 진행 :

type T0 = Exclude<'a' | 'b' | 'c' , 'a' | 'b'> // 'c'
type T1 = Pick<OriginalType, T0>               // { c: number; }
type T2 = T1 & {a: number, b: number }         // { a: number; b: boolean; c: number; }

@zSkycat의 대답을 조금 확장하면 두 개의 객체 유형을 받아들이고 첫 번째 구성원을 재정의하는 두 번째 구성원과 병합 된 유형을 반환하는 제네릭을 만들 수 있습니다.

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type Merge<M, N> = Omit<M, Extract<keyof M, keyof N>> & N;

interface A {
    name: string;
    color?: string;
}

// redefine name to be string | number
type B = Merge<A, {
    name: string | number;
    favorite?: boolean;
}>;

let one: A = {
    name: 'asdf',
    color: 'blue'
};

// A can become B because the types are all compatible
let two: B = one;

let three: B = {
    name: 1
};

three.name = 'Bee';
three.favorite = true;
three.color = 'green';

// B cannot become A because the type of name (string | number) isn't compatible
// with A even though the value is a string
// Error: Type {...} is not assignable to type A
let four: A = three;

같은 사건을 해결할 수있는 가능성을 조사하는 데 하루를 보내는 것이 재밌습니다. 이런 식으로 할 수 없다는 것을 알았습니다.

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

원인 모듈은 응용 프로그램에서 사용 가능한 모든 유형에 대해 알지 못할 수 있습니다. 그리고 모든 곳에서 모든 것을 이식하고 이와 같은 코드를 수행하는 것은 매우 지루합니다.

export interface A {
    x: A | B | C | D ... Million Types Later
}

자동 완성이 잘 작동하도록 나중에 유형을 정의해야합니다.


따라서 약간의 속임수를 쓸 수 있습니다.

// a.ts - module
export interface A {
    x: string;
}

재정의가 필요하지 않은 경우 자동 완성 작업을 허용하는 일부 유형은 기본적으로 그대로 두었습니다.

그때

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

Disable stupid exception here using @ts-ignore flag, saying us the we doing something wrong. And funny thing everything works as expected.

In my case I'm reducing the scope vision of type x, its allow me doing code more stricted. For example you have list of 100 properties, and you reduce it to 10, to avoid stupid situations

ReferenceURL : https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file

반응형