TypeScript에서 전역 변수 생성
JavaScript에서는 다음과 같이 할 수 있습니다.
something = 'testing';
그리고 또 다른 파일:
if (something === 'testing')
그리고 그것은 가질 것이다.something정의됩니다(올바른 순서로 호출된 경우).
TypeScript에서 어떻게 해야 하는지 모르겠어요.
이것이 내가 시도했던 것이다.
.d.ts 파일의 경우:
interface Window { something: string; }
그런 다음 main.ts 파일에서 다음을 수행합니다.
window.something = 'testing';
다른 파일:
if (window.something === 'testing')
그리고 이것은 효과가 있다.하지만 나는 이 모든 것을 잃고 싶다.window.를 .somethingTypeScript 서 type type type type type type type type type type type type type type type?
(누군가 관심을 가질 경우를 대비해서 어플리케이션 로깅을 설정하려고 합니다.할 수 좋겠다.log.Debug오브젝트를 Import 및 작성할 필요 없이 모든 파일에서 작업을 수행할 수 있습니다.
이것이 미래입니다.
에는 TypeScript의 두 종류가 .scopes
글로벌 스코프
파일에 또는 행이 없는 경우 이 파일은 글로벌 범위에서 실행되어 파일 외부에 모든 선언이 표시됩니다.
따라서 다음과 같은 글로벌 변수를 생성합니다.
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
모든 마법은 에서 나온다.
var를 바꿉니다체하하varlet★★★★★★★★★★★★★★★★★」const작동하지 않습니다.
모듈 스코프
파일에 또는 행이 있는 경우 이 파일은 선언 병합을 통해 글로벌하게 확장해야 하는 자체 범위 내에서 실행됩니다.
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
의 내부.d.ts 파일( file)
type MyGlobalFunctionType = (name: string) => void
브라우저에서 작업할 경우 브라우저 창 컨텍스트에 구성원을 추가합니다.
interface Window {
myGlobalFunction: MyGlobalFunctionType
}
노드에 대해서도 같은 생각JS:
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
다음으로 루트 변수(실제로 윈도 또는 글로벌)를 선언합니다.
declare const myGlobalFunction: MyGlobalFunctionType;
후, 의 럼럼 then then then .ts파일이지만 부수적인 효과로 Import된 파일은 실제로 구현됩니다.
global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};
마지막으로 코드베이스의 다른 곳에서 다음 중 하나를 사용하여 사용합니다.
global/* or window */.myGlobalFunction("Kevin");
myGlobalFunction("Kevin");
수정 방법은 다음과 같습니다.
순서:
- custom.d.ts 등의 글로벌 네임스페이스를 다음과 같이 선언했습니다.
declare global {
namespace NodeJS {
interface Global {
Config: {}
}
}
}
export default global;
- 위에서 작성한 파일을 다음과 같이 "tsconfig.json"에 매핑합니다.
"typeRoots": ["src/types/custom.d.ts" ]
- 위에서 작성한 글로벌 변수를 다음 파일 중 하나로 가져옵니다.
console.log(global.config)
주의:
typescript 버전: "3.0.1"
이 경우 어플리케이션을 기동하기 전에 글로벌 변수를 설정해야 합니다.필요한 설정 속성을 취득할 수 있도록 종속 객체 전체에 변수가 액세스해야 합니다.
이게 도움이 됐으면 좋겠네요!
감사해요.
여기에 게재된 텍스트는 Node.js의 TypeScript와 Global Variables의 짧은 버전입니다.
TypeScript 3.4 출시 이후 문서화된 방법이 있습니다.
""을 .global.d.ts하다★★★★
- var 를 사용하려면 이 기능이 필요합니다(자세한 내용은 typescriptlang.org 참조).
- ★
export {}가 " " " 가 됩니다any
declare global {
var Config: {
Foo: string;
};
var Foo: string;
}
export { };
에 tsconfig.json에 합니다.include ★★★★★★★★★★★★★★★★★」exclude하다
"include": [
"src/**/*.ts",
],
"exclude": [
"node_modules",
"<node_internals>/**",
"bin/**"
]
변수를 사용하려면 다음과 같은 작업을 수행합니다.
import * as Logger from './logger';
// Initialize early
global.log = Logger;
// Use it
log.Info("Booting system...");
즐기세요 :)
JavaScript와 TypeScript를 조합하여 사용하면 동작하는 방법을 찾았습니다.
logging.d.ts:
declare var log: log4javascript.Logger;
로그 확인js:
log = null;
초기화 어플리케이션
import './log-declaration.js';
// Call stuff to actually setup log.
// Similar to this:
log = functionToSetupLog();
이를 통해 글로벌 범위에 포함되며 TypeScript가 이를 인식합니다.그래서 내 모든 파일에 사용할 수 있습니다.
:이은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★allowJsTypeScript true 라고 입력합니다.
만약 누군가가 순수한 TypeScript 솔루션을 올린다면 저는 그것을 받아들이겠습니다.
나는 이것만 사용한다.
import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;
제대로 된 방법을 찾기 위해 몇 시간이나 걸렸어요.제 경우 글로벌 "log" 변수를 정의하려고 합니다.이러한 순서는 다음과 같습니다.
을 합니다.tsconfig.json을 src/types네, node_node- 네, 그렇습니다.
...other stuff...
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
) 2) 파일 생성src/types/global.d.ts다음 콘텐츠(가져오기 없음!-중요합니다)를 사용하여 자유롭게 변경 가능any + 를 사용합니다.window합니다.NodeJS「CHANGE MANGE:」
/**
* IMPORTANT - do not use imports in this file!
* It will break global definition.
*/
declare namespace NodeJS {
export interface Global {
log: any;
}
}
declare var log: any;
3) 사용 / 사용 3) 사용 가능 / 사용 가능 / 사용 가능log다음 중 하나:
// in one file
global.log = someCoolLogger();
// in another file
log.info('hello world');
// or if its a variable
global.log = 'INFO'
, 그럼 이제 ' 낫다'에 대한 다른 을 확장해 .globalThis(MDN 및 TypeScript 3.4 노트 참조) 동작이 상당히 혼란스러웠기 때문에 좀 더 구체적인 예(JavaScript와 혼합되지 않은 TypeScript만 해당)가 있습니다.모든 예는 Nodejs에서 실행됩니다.v12.14.1 TypeScript © TypeScriptVersion 4.2.3.
글로벌 범위에서 가장 심플한 케이스
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// output
// PROD
// PROD
★★★★★★★★★★★★★★★★★★★★★★★★」import ★★★★★★★★★★★★★★★★★」export글로벌 스코프 파일입니다.위의 TypeScript 코드를 오류 없이 컴파일할 수 있습니다.다음 명령어를 사용해야 합니다.var.★★★★★★ 。leterror TS2339: Property 'ENVIRONMENT' does not exist on type 'typeof globalThis'.
★★★★★★★★★★★★?declare는 다음과 같이 동작합니다.
var ENVIRONMENT: string;
ENVIRONMENT = 'DEV';
globalThis.ENVIRONMENT = 'PROD';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// output
// DEV
// PROD
"Nodejs" "Nodejs" 에서 나온 것입니다.v12.14.1 Chrome로 컴파일 한 후)로해, 의 출력 「(JS)」로 테스트했습니다.PROD ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★globalThis★★★★★★★★★★★★★★★★★★.
모듈 범위에서의 간단한 케이스
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
export {};
「 」를하면,export파일이 , 「」를 슬로우 합니다.error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.해결책은 글로벌 범위를 확대하는 것입니다.
declare global {
var ENVIRONMENT: string;
}
globalThis.ENVIRONMENT = 'PROD';
console.log(globalThis.ENVIRONMENT);
export {};
아직 사용하셔야 합니다.var, 그렇지 않으면,error TS2339: Property 'ENVIRONMENT' does not exist on type 'typeof globalThis'..
부작용수입
// ./main.ts
import './environment_prod';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// ./environment_prod.ts
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
또는
// ./environment_prod.ts
declare global {
var ENVIRONMENT: string;
}
globalThis.ENVIRONMENT = 'PROD';
export {}; // Makes the current file a module.
2개의 파일을 브라우저화하다
둘 다라고 가정하자.main.ts그리고.environment_prod.ts엔트리 파일입니다.Browserify는 그것들을 (JS로 컴파일된 후) 로컬 스코프 함수로 래핑합니다.이 함수는 다음과 같은 기능을 사용해야 합니다.globalThis.
// ./main.ts
declare var ENVIRONMENT: string;
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// ./environment_prod.ts
declare var ENVIRONMENT: string;
globalThis.ENVIRONMENT = 'PROD';
그러나 변수 이름이나 유형 이름의 오타를 방지하기 위해 선언 파일을 공유하는 것이 더 안전합니다. 선언 파일은 두 항목 파일로 가져올 수 있습니다.
// ./main.ts
import './environment';
console.log(ENVIRONMENT);
console.log(globalThis.ENVIRONMENT);
// ./environment_prod.ts
import './environment';
globalThis.ENVIRONMENT = 'PROD';
// ./environment.ts
type Environment = 'PROD' | 'DEV' | 'LOCAL';
declare var ENVIRONMENT: Environment;
해 주세요.browserify environment_prod.js main.js > bin.js
또한 여기에서 정답을 확인하십시오.
// global.d.ts
export const thisIsAModule = true; // <-- definitely in a module
declare global {
var foo: string;
}
그래, 네가 한 짓보다 더 추한 짓일 거야 하지만 어쨌든...
하지만 나도 마찬가지니까...
TypeScript로 할 수 은 TypeScript를 입니다.eval
declare var something: string;
eval("something = 'testing';")
그리고 나중에 당신은 할 수 있을 것이다.
if (something === 'testing')
않습니다.또, 「TypeScript」는 「TypeScript」라고 하는 입니다.declare varTypeScript 。
변경할 수 없는 기존 .js 파일을 사용하기 위해 lodash를 글로벌하게 만들어야 했습니다.
이게 효과가 있다는 걸 알게 되었습니다
import * as lodash from 'lodash';
(global as any)._ = lodash;
입니다.
https://stackoverflow.com/a/12709880/15859431에서 찾았습니다.
declare global {
interface Window {
myGlobalFunction: myGlobalFunction
}
}
이 스레드에 기재되어 있듯이, 이것은 나에게 유효합니다.
declare let something: string;
something = 'foo';
Dima V의 답변에 대한 추가 사항으로, 이것은 제가 이 일을 하기 위해 한 것입니다.
// First declare the window global outside the class
declare let window: any;
// Inside the required class method
let globVarName = window.globVarName;
노드 앱 및 유형 설명에 대한 전역 변수를 생성하는 방법입니다.
을 「파일명」이라고 .typings/index.ts
declare global {
var countSkipped: number;
var countProcessed: number;
var countLibUsedByFile: Record<string, number>;
}
export {};
일부 프로토타입을 재정의하는 경우 문자열 프로토타입을 위한 타이프스크립트 정의를 추가하는 방법을 소개합니다.
declare global {
interface String {
blue(): string;
yellow(): string;
green(): string;
red(): string;
}
}
export {};
위 문자열의 샘플 프로토타입입니다.
String.prototype.blue = function () {
return `\x1b[36m${this}\x1b[0m`;
};
String.prototype.yellow = function () {
return `\x1b[33m${this}\x1b[0m`;
};
String.prototype.green = function () {
return `\x1b[32m${this}\x1b[0m`;
};
String.prototype.red = function () {
return `\x1b[31m${this}\x1b[0m`;
};
먼저 글로벌 변수를 선언합니다.이렇게
declare global {
var options: {
billingAddress: {
country: string;
state: string;
city: string;
postcode: string;
street1: string;
street2: string;
};
mandatoryBillingFields: {
country: boolean;
state: boolean;
city: boolean;
postcode: boolean;
street1: boolean;
street2: boolean;
};
};
}
함수에서는 이렇게 사용할 수 있습니다.
const updateGlobalVariable = () => {
window.options = {
billingAddress: {
country: 'US',
state: 'NY',
city: 'New York',
postcode: '12345',
street1: 'Suite 1234',
street2: 'Some Road',
},
mandatoryBillingFields: {
country: true,
state: true,
city: true,
postcode: true,
street1: true,
street2: false,
},
};
};
이것을 사용하고 있습니다.
interface Window {
globalthing: any;
}
declare var globalthing: any;
언급URL : https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript
'programing' 카테고리의 다른 글
| wp_list_filength()가 작동하지 않습니다. (0) | 2023.03.08 |
|---|---|
| Swift 개체를 JSON으로 직렬화 또는 변환하려면 어떻게 해야 합니까? (0) | 2023.03.08 |
| json 파일에 데이터를 추가하는 방법 (0) | 2023.03.08 |
| 매우 큰 HTTP 요구 대 다수의 작은 요구 (0) | 2023.03.08 |
| Wordpress Admin에서 게시 ID를 가져오는 방법 (0) | 2023.03.08 |