TypeScript에서 가져오기 및 설정
속성의 get 및 set 메서드를 생성하려고 합니다.
private _name: string;
Name() {
get:
{
return this._name;
}
set:
{
this._name = ???;
}
}
값을 설정하는 키워드가 뭐죠?
TypeScript는 ECMAScript4/ActionScript3와 같은 getter/setter 구문을 사용합니다.
class foo {
private _bar: boolean = false;
get bar(): boolean {
return this._bar;
}
set bar(value: boolean) {
this._bar = value;
}
}
이 하려면 TypeScript 을 대상으로 하고 있는지 .「 TypeScript는 ECMAScript5 이후입니다.컴파일러를 하고 있는 를 합니다.--target
이렇게 깃발을 올립니다.
tsc --target ES5
Visual Studio를 사용하는 경우 프로젝트 파일을 편집하여 TypeScriptCompile 빌드 도구의 구성에 플래그를 추가해야 합니다.여기서 확인할 수 있습니다.
5를 이 JavaScript가됩니다.Object.defineProperty()
★★★★★★ 。
var foo = (function () {
function foo() {
this._bar = false;
}
Object.defineProperty(foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (value) {
this._bar = value;
},
enumerable: true,
configurable: true
});
return foo;
})();
최신 버전의 EcmaScript에서는 원본 TypeScript와 더 유사한 코드가 생성됩니다.예를 들어, EcmaScript 2017을 타겟으로 하면 다음과 같은 결과를 얻을 수 있습니다.
"use strict";
class foo {
constructor() {
this._bar = false;
}
get bar() {
return this._bar;
}
set bar(value) {
this._bar = value;
}
}
그래서 이걸 사용하기 위해서
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
과 같이 단순히 @DanFromGermany와 같은 foo.bar = true
세터와 게터 쌍을 갖는 것은 과잉 살상입니다.나중에 속성을 읽거나 쓸 때마다 로깅과 같은 작업을 수행해야 하는 경우 언제든지 추가할 수 있습니다.
getters를 사용하여 읽기 전용 속성을 구현할 수 있습니다.다음은 getter가 읽기 전용 및 옵션 유형과 어떻게 상호 작용하는지도 보여 주는 예입니다.
//
// type with optional readonly property.
// baz?:string is the same as baz:string|undefined
//
type Foo = {
readonly bar: string;
readonly baz?: string;
}
const foo:Foo = {bar: "bar"}
console.log(foo.bar) // prints 'bar'
console.log(foo.baz) // prints undefined
//
// interface with optional readonly property
//
interface iFoo {
readonly bar: string;
readonly baz?: string;
}
const ifoo:iFoo = {bar: "bar"}
console.log(ifoo.bar) // prints 'bar'
console.log(ifoo.baz) // prints undefined
//
// class implements bar as a getter,
// but leaves off baz.
//
class iBarClass implements iFoo {
get bar() { return "bar" }
}
const iBarInstance = new iBarClass()
console.log(iBarInstance.bar) // prints 'bar'
console.log(iBarInstance.baz) // prints 'undefined'
// accessing baz gives warning that baz does not exist
// on iBarClass but returns undefined
// note that you could define baz as a getter
// and just return undefined to remove the warning.
//
// class implements optional readonly property as a getter
//
class iBazClass extends iBarClass {
private readonly _baz?: string
constructor(baz?:string) {
super()
this._baz = baz
}
get baz() { return this._baz; }
}
const iBazInstance = new iBazClass("baz")
console.log(iBazInstance.bar) // prints bar
console.log(iBazInstance.baz) // prints baz
Ezward는 이미 좋은 답변을 제공했지만, 댓글 중 하나가 사용법을 묻는다는 것을 알게 되었습니다.이 질문을 우연히 접하게 된 저 같은 분들을 위해 Typescript 웹사이트의 getters 및 setters에 관한 공식 문서에 대한 링크를 갖는 것이 유용하다고 생각합니다.또한 변경이 이루어졌을 때 항상 최신 상태를 유지하고 사용 예를 보여 줍니다.
http://www.typescriptlang.org/docs/handbook/classes.html
특히 익숙하지 않은 사용자에게는 'get'이라는 단어를 getter에 대한 호출에 포함시키지 않는다는 점에 유의하십시오(또한 setter에 대해서도 마찬가지입니다.
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
이 조작은, 다음과 같이 하십시오.
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
다음과 같은 클래스가 주어집니다.
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
개인 '_bar' 속성의 'bar' getter가 호출됩니다.
다음은 올바른 방향을 제시하기 위한 작업 예입니다.
class Foo {
_name;
get Name() {
return this._name;
}
set Name(val) {
this._name = val;
}
}
JavaScript의 getters와 setters는 일반적인 함수입니다.setter는 설정되는 값이 값인 파라미터를 취하는 함수입니다.
이거 쓸 수 있어
class Human {
private firstName : string;
private lastName : string;
constructor (
public FirstName?:string,
public LastName?:string) {
}
get FirstName() : string {
console.log("Get FirstName : ", this.firstName);
return this.firstName;
}
set FirstName(value : string) {
console.log("Set FirstName : ", value);
this.firstName = value;
}
get LastName() : string {
console.log("Get LastName : ", this.lastName);
return this.lastName;
}
set LastName(value : string) {
console.log("Set LastName : ", value);
this.lastName = value;
}
}
TS는 오브젝트 속성이 오브젝트 외부에서 액세스(게터) 또는 갱신(세터)하는 방법을 보다 효과적으로 제어할 수 있도록 하는 게터 및 세터를 제공합니다.속성을 직접 액세스하거나 업데이트하는 대신 프록시 함수가 호출됩니다.
예:
class Person {
constructor(name: string) {
this._name = name;
}
private _name: string;
get name() {
return this._name;
}
// first checks the length of the name and then updates the name.
set name(name: string) {
if (name.length > 10) {
throw new Error("Name has a max length of 10");
}
this._name = name;
}
doStuff () {
this._name = 'foofooooooofoooo';
}
}
const person = new Person('Willem');
// doesn't throw error, setter function not called within the object method when this._name is changed
person.doStuff();
// throws error because setter is called and name is longer than 10 characters
person.name = 'barbarbarbarbarbar';
왜 이렇게 혼란스러운지 알 것 같아요.예에서는, 「Getter」의 「」와「Setter」의 「」를 ._name
, 관련 클래스 변수 「와「getter」의 getter를 으로, Name
.
다음 사항을 고려하십시오.
class Car {
private tiresCount = 4;
get yourCarTiresCount(){
return this.tiresCount;
}
set yourCarTiresCount(count) {
alert('You shouldn\'t change car tire count')
}
}
위의 코드는 다음과 같습니다.
get
★★★★★★★★★★★★★★★★★」set
getter의yourCarTiresCount
(용은 아닙니다).
getter는 다음과 같습니다.
function () {
return this.tiresCount;
}
세터는 다음과 같습니다.
function (count) {
alert('You shouldn\'t change car tire count');
}
가 할 마다, 할 때마다, 할 때마다, 할 수 있다, 할 수 있다, 할 수 있다, 할 수 있다, 할 수 있다, 할 수 있다, 할 수 있다, 할 수 있다.new Car().yourCarTiresCount
runs , getter runs . 모든 ★★★★★★★★★★★★★★에 대해서new Car().yourCarTiresCount('7')
세터
- 개인용으로 설정자가 아닌 getter를 간접적으로 생성한다.
tireCount
.
을 만드는 합니다. reserved는 reserved 입니다.유보하다get
★★★★★★★★★★★★★★★★★」set
★★★★★★★★★★★★★★★★★★.
class Name{
private _name: string;
getMethod(): string{
return this._name;
}
setMethod(value: string){
this._name = value
}
get getMethod1(): string{
return this._name;
}
set setMethod1(value: string){
this._name = value
}
}
class HelloWorld {
public static main(){
let test = new Name();
test.setMethod('test.getMethod() --- need ()');
console.log(test.getMethod());
test.setMethod1 = 'test.getMethod1 --- no need (), and used = for set ';
console.log(test.getMethod1);
}
}
HelloWorld.main();
반환 수 .get getMethod1() {
get getMethod1() {
return this._name;
}
제시된 예에 따르면 데이터 객체를 전달하고 get()을 통해 해당 객체의 속성을 가져오려면 데이터 객체는 일반적이므로 일반 유형을 사용해야 합니다.
export class Attributes<T> {
constructor(private data: T) {}
get = <K extends keyof T>(key: K): T[K] => {
return this.data[key];
};
set = (update: T): void => {
// this is like spread operator. it will take this.data obj and will overwrite with the update obj
// ins tsconfig.json change target to Es6 to be able to use Object.assign()
Object.assign(this.data, update);
};
getAll(): T {
return this.data;
}
}
< T >는 범용 타입입니다.인스턴스를 초기화합니다.
const myAttributes=new Attributes({name:"something",age:32})
myAttributes.get("name")="something"
이 구문에 주의해 주십시오.
<K extends keyof T>
이것을 사용하려면 , 다음의 2개의 점에 주의할 필요가 있습니다.
1- 입력 문자열은 유형일 수 있습니다.
2-javascript의 모든 객체 속성은 기본적으로 문자열입니다.
gettype 인수 은 type 이 될 수 이 gettype을 할 수 . <K extends keyof T>
있는 의 오브젝트 상에서 get and set을 합니다.Proxy
도움이 될 수 있습니다.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
const target = {
message1: "hello",
message2: "everyone"
};
const handler3 = {
get: function (target, prop, receiver) {
if (prop === "message2") {
return "world";
}
return Reflect.get(...arguments);
},
};
const proxy3 = new Proxy(target, handler3);
console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world
주의: 이것은 새로운 API는 지원되지 않으며 오래된 브라우저에서는 필수 폴리필입니다.
getter & setter를 추가하는 예를 다음에 나타냅니다.
class Person {
private _age: number;
private _firstName: string;
private _lastName: string;
public get age() {
return this._age;
}
public set age(theAge: number) {
if (theAge <= 0 || theAge >= 200) {
throw new Error('The age is invalid');
}
this._age = theAge;
}
public getFullName(): string {
return `${this._firstName} ${this._lastName}`;
}
}
이 직접 TypeScript로 할 수 .false
설정에 는, 「 」의ts.config.json
.
{
"compilerOptions": {
"strict": true,
"strictPropertyInitialization": false
}
}
속성 - 완전 속성 초기화 -
strictPropertyInitialization
true로 설정하면 클래스 속성이 선언되었지만 생성자에 설정되지 않았을 때 TypeScript가 오류를 발생시킵니다.
이 경우 다음 링크에서 볼 수 있는 다른 사례도 고려해야 합니다.
class UserAccount {
name: string;
accountType = "user";
email: string;//Property 'email' has no initializer and is not definitely assigned in the constructor.
address: string | undefined;
constructor(name: string) {
this.name = name;
// Note that this.email is not set
}
}
this.name
는 특별히 설정되어 있습니다.
this.accountType
는 디폴트로 설정되어 있습니다.
this.email
설정되어 있지 않고, 에러가 발생합니다.
this.address
잠재적인 미정의로 선언되어 있기 때문에 설정할 필요가 없습니다.
컴파일러는 에러를 발생시키지 않습니다.strictPropertyInitialization
로.false
private _name : string;
public get name() : string {
return this._name;
}
public set name(v : string) {
this._name = v;
}
https://www.typescriptlang.org/docs/handbook/2/classes.html#--strictpropertyinitialization https://www.typescriptlang.org/tsconfig#strictPropertyInitialization
TypeScript 모듈을 사용하여 내보내는 getter를 추가하려는 경우 다음과 같은 작업을 수행할 수 있습니다.
// dataStore.ts
export const myData: string = undefined; // just for typing support
let _myData: string; // for memoizing the getter results
Object.defineProperty(this, "myData", {
get: (): string => {
if (_myData === undefined) {
_myData = "my data"; // pretend this took a long time
}
return _myData;
},
});
다른 파일에는 다음과 같은 내용이 있습니다.
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"
언급URL : https://stackoverflow.com/questions/12827266/get-and-set-in-typescript
'programing' 카테고리의 다른 글
iFrame의 각도, onLoad 함수 (0) | 2023.02.09 |
---|---|
Spring Boot에서 각 사용자의 환율 제한을 설정하려면 어떻게 해야 합니까? (0) | 2023.02.09 |
Data Contract Json Serializer 및 Enums (0) | 2023.02.09 |
스프링 부트 액추에이터 엔드포인트의 응답 MIME 유형 (0) | 2023.02.09 |
여기서 발생하는 오류는 처리되지 않습니다. (0) | 2023.02.09 |