code

TypeScript에서 "keyof typeof"는 무엇을 의미합니까?

starcafe 2023. 3. 19. 18:22
반응형

TypeScript에서 "keyof typeof"는 무엇을 의미합니까?

keyof typeofTypeScript의입니다.

예:

enum ColorsEnum {
    white = '#ffffff',
    black = '#000000',
}

type Colors = keyof typeof ColorsEnum;

마지막 행은 다음과 같습니다.

type Colors = "white" | "black"

하지만 어떻게 작동할까요?

typeof ColorsEnum"Object" 다음에 또 한 번.keyof "Object"★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★♪이치노

이해하다keyof typeofTypeScript 에서의 사용방법, 우선 리터럴 타입과 리터럴 타입의 결합에 대해 이해할 필요가 있습니다.그래서 먼저 이 개념들을 설명하고 나서 설명을 해드릴게요.keyof ★★★★★★★★★★★★★★★★★」typeof별적개후에 다시 after after 시 、 시 、 시 、 뵙 、 after 、 after 、 after 、 after 、 after 。enum질문에 대답할 수 있습니다.긴 답변이지만 예시는 이해하기 쉽다.


리터럴 타입

은 TypeScript의 보다 입니다.string,number ★★★★★★★★★★★★★★★★★」boolean를 들어."Hello World"는 입니다.string ,,string"Hello World""Hello World"입니다.string리터럴 타입입니다.

리터럴 타입은 다음과 같이 선언할 수 있습니다.

type Greeting = "Hello"

, 타입의 가 「」라고 하는 입니다.Greetingstring 가 value"Hello" 다른 것은 없다string다음 코드에 표시된 값 또는 기타 유형의 값:

let greeting: Greeting
greeting = "Hello" // OK
greeting = "Hi"    // Error: Type '"Hi"' is not assignable to type '"Hello"'

리터럴 타입 자체는 유용하지 않지만 유니언 타입, 타입 에일리어스 및 타입 가드와 조합하면 강력해집니다.

리터럴 타입의 결합 를 다음에 나타냅니다.

type Greeting = "Hello" | "Hi" | "Welcome"

으로 타입의 입니다.Greeting을 수 ."Hello","Hi" ★★★★★★★★★★★★★★★★★」"Welcome".

let greeting: Greeting
greeting = "Hello"       // OK
greeting = "Hi"          // OK
greeting = "Welcome"     // OK
greeting = "GoodEvening" // Error: Type '"GoodEvening"' is not assignable to type 'Greeting'

keyof

keyof T리터럴 타입의 조합인 새로운 타입을 제공합니다.이러한 리터럴타입은, 다음의 속성의 이름입니다.T 은 문자열의 이치노

들면 다음과 같은 해 보세요.interface:

interface Person {
    name: string
    age: number
    location: string
}

「 」의 keyofPerson는 다음 합니다.

type SomeNewType = keyof Person

★★★★★★★★★★★★★★★★★.SomeNewType의 조합입니다."name" | "age" | "location" 「」의Person.

이제 유형의 개체를 생성할 수 있습니다.SomeNewType:

let newTypeObject: SomeNewType
newTypeObject = "name"           // OK
newTypeObject = "age"            // OK
newTypeObject = "location"       // OK
newTypeObject = "anyOtherValue"  // Error...

keyof typeof 으로 함께

, 「 」는,typeof이치노에서는, 「」를 해 주세요.Person 유형을 있기 에, 「유형」, 「유형」을 할 수 밖에.keyofPerson.

그러나 다음과 같이 개체의 유형을 모르거나 값의 유형이 아닌 값만 있는 경우 어떻게 해야 할까요?

const bmw = { name: "BMW", power: "1000hp" }

하는 것은 기가 this this this this this this this this this this this this this this this this thiskeyof typeof★★★★★★ 。

typeof bmw하는 을 제시해 줍니다.{ name: string, power: string }

다음에 ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ.keyof연산자는 다음 코드와 같이 리터럴타입의 유니언을 제공합니다.

type CarLiteralType = keyof typeof bmw

let carPropertyLiteral: CarLiteralType
carPropertyLiteral = "name"       // OK
carPropertyLiteral = "power"      // OK
carPropertyLiteral = "anyOther"   // Error...

keyof typeof enum

TypeScript에서는 enum을 컴파일타입으로 사용하여 상수의 타입 안전을 확보하지만 실행 시 오브젝트로 취급됩니다.이는 TypeScript 코드가 JavaScript로 컴파일되면 플레인 객체로 변환되기 때문입니다.따라서 위의 사물에 대한 설명은 여기에도 해당됩니다.질문의 OP 예는 다음과 같습니다.

enum ColorsEnum {
    white = '#ffffff',
    black = '#000000',
}

서 ★★★★ColorsEnum실행 시 유형이 아닌 개체로 존재합니다. 이렇게 ,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아.keyof typeof다음 코드에 표시된 것과 같이 연산자를 조합합니다.

type Colors = keyof typeof ColorsEnum

let colorLiteral: Colors
colorLiteral = "white"  // OK
colorLiteral = "black"  // OK
colorLiteral = "red"    // Error...

keyof에서는 오브젝트 타입을 취득하여 오브젝트의 키를 받아들이는 타입을 반환합니다.

type Point = { x: number; y: number };
type P = keyof Point; // type '"x" || "y"'

const coordinate: P = 'z' // Type '"z"' is not assignable to type '"x" | "y"'.

TypeScript 유형을 사용하는 유형

typeof객체에서 type에서 되었을 때 .

  • 실행 시 javascript 값을 호출하면 type of를 사용하여 다음 중 하나를 반환합니다."undefined", "object", "boolean", "number", "bigint", "string", "symbol", "function"
  • TypeScript의 typeof는 type 값에서 호출되지만 type 식에서 javascript 값을 호출할 수도 있습니다.또한 javascript 객체의 유형을 추론할 수 있어 보다 상세한 객체 유형을 반환합니다.
type Language = 'EN' | 'ES'; 
const userLanguage: Language = 'EN';
const preferences = { language: userLanguage, theme: 'light' };

console.log(typeof preferences); // "object"
type Preferences = typeof preferences; // type '{language: 'EN''; theme: string; }'

두 번째가typeof preferences는 타입 으로, 는 TypeScript입니다.typeof자바스크립트

키 오브 타입

는 TypeScript의 개념이기 때문에 TypeScript의 버전이라고 부릅니다.typeof.

keyof typeof는 Javascript 객체의 유형을 추론하여 키의 조합인 유형을 반환합니다.키의 정확한 값을 추론할 수 있기 때문에 단순히 "문자열"을 반환하는 대신 리터럴 유형의 결합을 반환할 수 있습니다.

type PreferenceKeys = keyof typeof preferences; // type '"language" | "theme"'

enum된 「」를 합니다.object★★★★★★★★★★★★★★★★typeof 자동 은 이 타입입니다.enum.

으로 할 수 되었습니다.keyof 하다Colors둘 중 하나만 포함할 수 있습니다.

TypeScript에 대한 일반적인 오해

TypeScript는 JavaScript 런타임 위에 있는 유형 계층으로 설명되는 경우가 많습니다.유형과 값이 다른 평면에 사는 것처럼.그러나 TypeScript에서는 유형과 값을 동시에 지정할 수 있습니다.

이는 다음 경우에 해당됩니다.

  • 반,
  • enums,
  • 네임스페이스

하실 수 있나요?keyof

keyof이치노자바스크립트

합니까?keyof typeof

종류와 값을 동시에 취급하는 경우(클래스나 열거형 등), 특히 그 값의 종류에 관심이 있는 경우.

가장 간단한 예:

const foo = { bar: 42 }; // foo is a value
type Foo = typeof foo; // Foo is the type of foo

type KeyOfFoo = keyof Foo; // "keyof Foo" is the same as "keyof typeof foo", which is "bar"

일반적으로 다음과 같이 표시됩니다.

type A = keyof typeof B;

typeof Bpart는 TypeScript에 B의 유형을 확인하도록 지시합니다.B를 그 타입에 맞춘다고 생각하면 된다.2차원 물체를 1차원 공간에 던지는 것과 비슷합니다.

★★typeof B이기 때문에 '어울리다'를 사용할 수 .이제 를 사용할 수 있습니다.keyof위에.

클래스는 유형과 값입니다. '전화'를 사용할 .keyof그 위에 올려놔요.

declare class Foo {
    static staticProperty: string;

    dynamicProperty: string;
}

type Constructor = typeof Foo;
type Instance = Foo;

type A = keyof Constructor; // "prototype" | "staticProperty"
type B = keyof Instance; // "dynamicProperty"

「」를 사용해 .typeof keyof 해서, 이렇게 수 요.keyof인스턴스 유형 및 생성자 유형에 대해 비교합니다.

값의 유형을 찾기 위해 작업 유형을 사용합니다.예:

const user = {
   getPersonalInfo(){},
   getLocation(){}
}

여기서 user는 값이기 때문에 여기서 연산자 유형은 유용합니다.

type userType = typeof user

여기서 userType은 사용자가 getPersonalInfo와 getLocation의 두 가지 속성을 가진 개체이며 둘 다 함수가 void를 반환한다는 유형 정보를 제공합니다.

사용자 키를 찾으려면 다음 키를 사용할 수 있습니다.

type userKeys = keyof userType

userKeys= 'getPersonalInfo'| 'getLocation'이라고 되어 있습니다.

할 해야 합니다.type userKeys = keyof user'user'는 값을 나타내지만 여기서 유형으로 사용되고 있습니다. '사용자 유형'을 의미했나요?

언급URL : https://stackoverflow.com/questions/55377365/what-does-keyof-typeof-mean-in-typescript

반응형