programing

유형 스크립트: 인터페이스의 상수

sourcejob 2023. 6. 18. 13:07
반응형

유형 스크립트: 인터페이스의 상수

유형 스크립트에서 인터페이스에 상수를 배치하려면 어떻게 해야 합니까?자바와 마찬가지로 다음과 같습니다.

interface OlympicMedal {
  static final String GOLD = "Gold";
  static final String SILVER = "Silver";
  static final String BRONZE = "Bronze";
}

인터페이스에서 값을 선언할 수 없습니다.

모듈에서 값을 선언할 수 있습니다.

module OlympicMedal {
    export var GOLD = "Gold";
    export var SILVER = "Silver";
}

TypeScript의 다음 릴리스에서는 다음을 사용할 수 있습니다.const:

module OlympicMedal {
    export const GOLD = "Gold";
    export const SILVER = "Silver";
}

OlympicMedal.GOLD = 'Bronze'; // Error

유형 대신 인터페이스의 값을 사용하면 됩니다(아래 참조).

export interface TypeX {
    "pk": "fixed"
}

let x1 : TypeX = {
    "pk":"fixed" // this is ok
}

let x2 : TypeX = {
    "pk":"something else" // error TS2322: Type '"something else"' is not assignable to type '"fixed"'.
}

아무도 어떻게 해야 하는지에 대한 실제 답을 주지 않았기 때문에.interface(예를 들어 인터페이스/클래스 병합에 사용).

interface Medals {
  GOLD: 'gold';
  SILVER: 'silver';
  BRONZE: 'bronze';
}

이것은 만들 것입니다.

const a: Medals = { ... }
// type of a.GOLD is the literal 'gold'

비록 당신이 사용을 고려해야 합니다.enum또는const medals = { ...definition } as const아니면 심지어는class.

부록: 객체, 어레이 및 클래스

const 배열 및 const 객체는 다음과 같이 수행할 수 있습니다.

const constArray = ['array', 'of', 'emperor', 'Constantine'] as const;
const constObj = { gold: 'GOLD', silver: 'SILVER', bronze: 'BRONZE' } as const;

interface Constants {
  constArray: typeof constArray;
  constObj: typeof constObj;
}

const obj: Constants = {} as any;
const str = obj.constArray[3]; // str has type 'Constantine'
const gold = obj.constObj.gold; // gold has type 'gold'

클래스 기반 접근 방식의 경우

class Medals {
  static readonly GOLD = 'gold';
  static readonly SILVER = 'silver';
  static readonly BRONZE = 'bronze';
}

// Medals.GOLD has literal type 'gold'

인터페이스에 상수를 두는 방법에는 모듈과 인터페이스를 모두 동일한 이름으로 정의하는 방법이 있습니다.

다음에서는 인터페이스 선언이 모듈과 병합되어 올림픽 메달이 값, 네임스페이스 및 유형이 됩니다.이것이 당신이 원하는 것일 수도 있습니다.

module OlympicMedal {
    export const GOLD = "Gold";
    export const SILVER = "Silver";
}

interface OlympicMedal /* extends What_you_need */ {
    myMethod(input: any): any;
}

이것은 Typescript 2.x에서 작동합니다.

여기에 표시된 것처럼 인터페이스에서 상수를 설정하는 권장 방법은 다음과 같습니다.

export class Constants {
  public static readonly API_ENDPOINT = 'http://127.0.0.1:6666/api/';
  public static readonly COLORS = {
    GOLD: 'Gold',
    SILVER: 'Silver',
    BRONZE: 'Bronze'
  };
}

모듈 및 네임스페이스는 린터를 통해 많은 경고를 보내기 때문에 TSLinter에서 설정을 비활성화하지 않고 상수를 정의하는 기본 방법입니다.

이것은 효과가 있는 것 같습니다.

class Foo {
  static readonly FOO="bar"
}

export function foo(): string {
  return Foo.FOO
}

이와 같이 개인 상수도 가질 수 있습니다.인터페이스에 정적 멤버가 있을 수 없는 것 같습니다.

언급URL : https://stackoverflow.com/questions/26471239/typescript-constants-in-an-interface

반응형